how to remove class of a specific element inside an element - javascript

function myfunction() {
let items = document.querySelectorAll("#ol li"),
array = [];
for (var i = 0; i < items.length; i++) {
array.push(items[i].innerHTML);
}
for (var i = 0; i < items.length; i++) {
items[i].onclick = function() {
document.getElementById("content").innerHTML = this.innerHTML;
}
};
}
<ol id="ol">
<li class="li">
<span class="x">hello</span>
<span class="xx">testing</span>
</li>
<li class="li">
<span class="x">hello2</span>
<span class="xx">testing2</span>
</li>
<li class="li">
<span class="x">hello3</span>
<span class="xx">testing4</span>
</li </ol>
<div id="content"></div>
<button onclick="myfunction()">click</button>
When I click on one of the lists, the code will put the innerHTML of the list that I clicked into a div, but I also want to remove the class of the spans in the list that is inside the div
How can I do this?
ive tried this but it doesnt work
function myfunction() {
let items = document.querySelectorAll("#ol li"),
array = [];
for (var i = 0; i < items.length; i++) {
array.push(items[i].innerHTML);
}
for (var i = 0; i < items.length; i++) {
items[i].onclick = function() {
document.getElementById("content").innerHTML = this.innerHTML;
const spanInsideDiv = document.querySelector("#content .li .x")
for (var i = 0; i < spanInsideDiv.length; i++) {
spanInsideDiv[i].classList.remove('li');
}
};
}

At the moment your simply copying all the innerHTML to the target <div>. After this happened we can get a HTMLCollection - more or less an array - of all the <span> elements inside using:
document.getElementById("content").getElementsByTagName("span");
Now we can simply loop over the collection and remove all the css classes by calling removeAttribute("class") on each one. This will remove any css class while keeping your original spans intact.
Here's an example:
function myfunction() {
let items = document.querySelectorAll("#ol li"),
array = [];
for (var i = 0; i < items.length; i++) {
array.push(items[i].innerHTML);
}
for (var i = 0; i < items.length; i++) {
items[i].onclick = function() {
document.getElementById("content").innerHTML = this.innerHTML;
let span = document.getElementById("content").getElementsByTagName("span");
for (var a = 0; a < span.length; a++) {
span[a].removeAttribute("class");
}
}
};
}
<ol id="ol">
<li class="li">
<span class="x">hello</span>
<span class="xx">testing</span>
</li>
<li class="li">
<span class="x">hello2</span>
<span class="xx">testing2</span>
</li>
<li class="li">
<span class="x">hello3</span>
<span class="xx">testing4</span>
</li>
</ol>
<div id="content"></div>
<button onclick="myfunction()">click</button>

Related

Getting Random Nulls on .querySelector() in for Loop

<div id="agg-filter-buttons">
<button class="btn filter-btn" onclick="filterSelection(event)"><span data-
value="freespins">Free Spins <div class="num-brands"></div> </span></button>
<button class="btn filter-btn" onclick="filterSelection(event)"> <span data-value="bigbonus">Big Bonus <div class="num-brands"></div> </span></button> </div>
enter code here
</div>
<div class="brand-row the-table-row all row-1 filterDiv bigbonus newPlay show">
Row 1
</div>
<div class="brand-row the-table-row all row-2 filterDiv freespins newPlay show">
Row 2
</div>
filterSelection();
function filterSelection(e) {
var x, i, c;
x = document.getElementsByClassName("filterDiv");
var allBtns = document.getElementsByClassName("filter-btn")
for(i = 0; i<allBtns.length; i++){
let rowsAffected = allBtns[i].querySelector('.num-brands');
rowsAffected.innerText = '';
}
c = "all";
if(e && e.target.dataset){
c = e.target.dataset.value ? e.target.dataset.value : "all";
}
const numBrands = [];
for (i = 0; i < x.length; i++) {
x[i].classList.remove('show');
void x[i].offsetWidth;
if (x[i].classList.contains(c)) {
x[i].classList.add('show');
numBrands.push(i);
}
}
if(e && e.target){
e.srcElement.children[0].innerText = ` (${numBrands.length})`;
}
}
// Add active class to the current control button (highlight it)
var btnContainer = document.getElementById("agg-filter-buttons");
var btns = btnContainer.getElementsByClassName("filter-btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function($this) {
var current = document.querySelectorAll(".active-btn");
current[0].className = current[0].className.replace(" active-btn", "");
this.className += " active-btn";
});
}
var filter = document.getElementById('agg-filter-buttons');
filter.addEventListener('click', function(){
document.getElementsByClassName('section--btable')[0].classList.add('flash');
});
filterSelection();
function filterSelection(e) {
var x, i, c;
x = document.getElementsByClassName("filterDiv");
var allBtns = document.getElementsByClassName("filter-btn")
for (i = 0; i < allBtns.length; i++) {
let rowsAffected = allBtns[i].querySelector('.num-brands');
rowsAffected.innerText = '';
}
c = "all";
if (e && e.target.dataset) {
c = e.target.dataset.value ? e.target.dataset.value : "all";
}
const numBrands = [];
for (i = 0; i < x.length; i++) {
x[i].classList.remove('show');
void x[i].offsetWidth;
if (x[i].classList.contains(c)) {
x[i].classList.add('show');
numBrands.push(i);
}
}
if (e && e.target) {
e.srcElement.children[0].innerText = ` (${numBrands.length})`;
}
}
// Add active class to the current control button (highlight it)
var btnContainer = document.getElementById("agg-filter-buttons");
var btns = btnContainer.getElementsByClassName("filter-btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function($this) {
var current = document.querySelectorAll(".active-btn");
current[0].className = current[0].className.replace(" active-btn", "");
this.className += " active-btn";
});
}
var filter = document.getElementById('agg-filter-buttons');
filter.addEventListener('click', function() {
document.getElementsByClassName('section--btable')[0].classList.add('flash');
});
<div id="agg-filter-buttons">
<button class="btn filter-btn" onclick="filterSelection(event)"><span data-
value="freespins">Free Spins <div class="num-brands"></div> </span></button>
<button class="btn filter-btn" onclick="filterSelection(event)"> <span data-value="bigbonus">Big Bonus <div class="num-brands"></div> </span></button> </div>
enter code here
</div>
>
<div class="brand-row the-table-row all row-1 filterDiv bigbonus newPlay show">
Row 1
</div>
<div class="brand-row the-table-row all row-2 filterDiv freespins newPlay show">
Row 2
</div>
So I have a table with rows. These are filtered with the filter buttons. When you click a filter button it shows only the rows with the same name in its class. This works and populates the button with how many rows are affected.
However this breaks occasionally and I have no idea why.
the Variable rowsAffected works until it becomes null for some unknown reason.
My guess is that the dom eventually doesnt load fast enough for the querySelector to be able to read it. But im not sure.. Any advice very welcome!
I have also added a fiddle
https://jsfiddle.net/8z56sxby/
Since you only care about the first .active-btn (because there is at most one), you can just use querySelector.
Make sure there is a current before you do anything with its classes.
Use element.classList.add and element.classList.remove to add or remove classes.
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.querySelector(".active-btn");
if (current) current.classList.remove("active-btn");
this.classList.add("active-btn");
});
}
Thankyou
The answer to this question was that clicks on my button were sometimes clicking child elements which were not setup to handle the click.
A silly mistake - that someone may find useful in the future.

How to add ID to <a href> on click using JavaScript

I have an HTML like this
How add ID to HTML href with javascript
<div class="tab">
exp
</div>
<div class="tab">
exp
</div>
<div class="tab">
exp
</div>
<script>
var els = document.getElementsByClassName("tab");
// loops els
for(var i = 0, x = els.length; i < x; i++) {
els[i].onclick = function(){
x = document.querySelector(".tab> a")
// do something
x.id = "expid";
}
}
</script>
I want to add the id to each tag when I click this. Pls help me. Thks so much
<div class="tabs">
... your html code.
</div>
const tabs = document.querySelector('.tabs')
tabs.addEventListener('click', event => {
const aTag = event.target
if (aTag.tagName !== 'A') return
aTag.id = `EXPID#${getIndexIn(aTag, tabs)}`
})
function getIndexIn(element, parent): number
What's the meaning to be it?
Your call to document.querySelector() always returns the first .tab > a link in the document. You can this.querySelector() to return the link in the DIV that you clicked on instead.
I've changed the code to use a class rather than ID, since you shouldn't have duplicate IDs.
Loop through all the DIVs. If it's the DIV that the user clicked on, add the class, otherwise remove it.
var els = document.getElementsByClassName("tab");
// loops els
for (var i = 0, x = els.length; i < x; i++) {
els[i].onclick = function() {
for (var j = 0; j < els.length; j++) {
x = els[j].querySelector("a");
if (els[j] == this) {
x.classList.add("expid");
} else {
x.classList.remove("expid");
}
}
}
}
.expid {
background-color: yellow;
}
<div class="tab">
exp
</div>
<div class="tab">
exp
</div>
<div class="tab">
exp
</div>
const anchors = document.getElementsByTagName('a');
const ids= [1,2,3,4,5];
let index =0 ;
for(let a of anchors ){
a.href=ids[index++]
}
you can try this way it's a cool and easiest what I do with pure js

javascript filter app not working all uls not being processed

this is a simple javascript filterable list but for some reason, the outer for loop is running only once but when I remove inner loop the outer loop runs fine
the filter is only running on first ul the other uls are being ignored
can someone correct the code
<div style="margin-left:40%; width:20%">
<h1>SEARCH</h1>
<input type="text" class="search">
<ul class="collection">
<li class="collection-item"><h2>A</h2></li>
<li class="collection-item">Adam</li>
<li class="collection-item">Alan</li>
<li class="collection-item">aspen</li>
<li class="collection-item">Andrew</li>
</ul>
<ul class="collection">
<li class="collection-item"><h2>B</h2></li>
<li class="collection-item">Bob</li>
<li class="collection-item">Builder</li>
<li class="collection-item">Brown</li>
<li class="collection-item">Brad</li>
</ul>
</div>
Javascript code:
var search = document.querySelector(".search");
var lists = document.querySelectorAll("ul");
var all_lis = document.querySelectorAll("li");
search.addEventListener('keyup', filter);
function filter(event) {
console.log("filtering....");
for (var i = 0; i < all_lis.length; i++) {
all_lis[i].style.display = "";
}
for (var i = 0; i < lists.length; i++) {
var ls = lists[i].querySelectorAll("li");
console.log(ls);
for (var i = 1; i < ls.length; i++) {
if (ls[i].textContent.toLowerCase().includes(event.target.value)) {
ls[i].style.display = "";
console.log(ls[i]);
} else {
ls[i].style.display = "none";
console.log(ls[i]);
}
}
}
}

Three js loops just in one

Hey i just wanted to do one loop which has in three buttons and three drop down lists. But I must created three list because when I connect them connect also drop down lists. My three loops looks like:
var arrow = document.getElementsByClassName('list_arrow');
var list = document.getElementsByClassName('list_panel');
for (var i = 0; i < arrow.length; i++) {
arrow[0].addEventListener('click', function() {
for (var i = 0; i < list.length; i++) {
list[0].classList.toggle('list_panel_open');
}
});
}
for (var i = 0; i < arrow.length; i++) {
arrow[2].addEventListener('click', function() {
for (var i = 0; i < list.length; i++) {
list[2].classList.toggle('list_panel_open');
}
});
}
for (var i = 0; i < arrow.length; i++) {
arrow[1].addEventListener('click', function() {
for (var i = 0; i < list.length; i++) {
list[1].classList.toggle('list_panel_open');
}
});
}
And how can I write this just in one loop?
You don't need the loop within the loops either:
for (var i = 0; i < arrow.length; i++) {
arrow[i].addEventListener('click', function() {
list[i].classList.toggle('list_panel_open');
// since all of the `i` numbers are the same
});
}
You should not combine 2 sets of queried elements like that. You are not guaranteed that the index in the array is the same everywhere. Instead set a attribute on the button(data-id). In the onClickElement handler I get the data-id and use it to toggle the target element.
var q = document.querySelectorAll.bind(document);
function toggleElement(id){
q("#" + id)[0].classList.toggle('hidden');
}
function onClickElement(){
var toggleId = this.getAttribute('data-id');
toggleElement(toggleId);
}
q('.arrow').forEach(function(element){
element.addEventListener('click', onClickElement);
});
.hidden{
display: none;
}
<button class="arrow" data-id="p1">1</button>
<button class="arrow" data-id="p2">2</button>
<button class="arrow" data-id="p3">3</button>
<br>
<br>
<div id="p1" class="panel hidden">Panel 1</div>
<div id="p2" class="panel hidden">Panel 2</div>
<div id="p3" class="panel hidden">Panel 3</div>

Delete <li>'s that have the same value in another <li>

If there were two <ul>'s, one called list_a and the other called list_b, using javascript and not using any libraries like jQuery, how would you delete the <li>'s in list_a that have the same value as those in list_b?
Heres the example HTML:
<ul id="list_a">
<li value="1">list_a_0</li>
<li value="8">list_a_8</li>
<li value="9">list_a_9</li>
</ul>
<ul id="list_b">
<li value="8">list_b_8</li>
<li value="9">list_b_9</li>
<li value="2">list_b_2</li>
</ul>
The end result should be:
<ul id="list_a">
<li value="1">list_a_0</li>
<!-- DELETED TWO <li>'s -->
</ul>
<ul id="list_b">
<li value="8">list_b_8</li>
<li value="9">list_b_9</li>
<li value="2">list_b_2</li>
</ul>
The javascript so far that I can build (that doesn't work) is:
window.onload=function()
{
init();
function init()
{
var listA = document.getElementById("list_a");
for(var i in listA.childNodes)
{
var x = listA.childNodes[i];
var listB = document.getElementById("list_b");
for(var j in listB.childNodes)
{
var y = listB.childNodes[j];
if(x.innerHTML == y.innerHTML)
listA.removeChild(listA);
}
}
}
}
Thanks!
DEMO: http://jsfiddle.net/rmXrZ/
window.onload = function() {
var listA = document.getElementById("list_a");
var listB = document.getElementById("list_b");
for (var i = 0; i < listA.children.length; i++) {
var x = listA.children[i];
for (var j = 0; j < listB.children.length; j++) {
var y = listB.children[j];
if (x.value == y.value) {
listA.removeChild(x);
i--;
}
}
}
}
Don't use for-in for iteration of numeric indices
Cache the DOM selection instead of re-selecting in the loop
Use .children instead of .childNodes to avoid text nodes between elements
Compare .value instead of .innerHTML
Remove x instead of listA
When an element is removed from listA, decrement i, because removal from the DOM means removal from the .children collection.
function init() {
var listA = document.getElementById("list_a");
var listB = document.getElementById("list_b");
for(var i =0; i<listA.children.length;i++) {
var x = listA.children[i];
for(var j in listB.children) {
var y = listB.children[j];
if(x.value == y.value)
x.parentNode.removeChild(x);
}
}
}
Avoid hitting the DOM on multiple occasions, also in this case children is a better choice of data.

Categories