var numbers = document.querySelectorAll("#box1 , #box2"); - javascript

I have problem with my javascript code
why that function didn't get the multiple id's
var numbers = document.querySelectorAll("#box1 , #box2");
for(i=0; i<10; i++){
var span = document.createElement('span')
span.textContent = i;
numbers.appendChild(span);
}
/////////////////////////
<div id="box1"></div>(this is the div where is doesn't get)

Unlike jQuery you cannot run an action of the entire node list (array of elements). You have to forEach all the elements.
var numbers = document.querySelectorAll("#box1 , #box2");
numbers.forEach(function(number) {
// this is almost exact copy of your code
for (i = 0; i < 10; i++) {
var span = document.createElement('span')
span.textContent = i;
number.appendChild(span);
}
})
<div id="box1"></div>
<div id="box2"></div>

why dont you use getElementById?
use querySelectorAll when you have many div with same classname
const box1 = document.getElementById("box1")
const box2 = document.getElementById("box2")
const box = document.querySelectorAll(".box")
const box_1 = document.querySelector("#box1")
const box_2 = document.querySelector("#box1")
<div id="box1" class="box"></div>
<div id="box2" class="box"></div>

Related

Find div by inner text and adding class

I am trying to find a specific div by its inner text to adding subsequently a class. How can i do it?
Example input
<div>First</div>
<div>Second</div>
<div>Third</div>
Desired output
<div>First</div>
<div class="check">Second</div>
<div>Third</div>
I hope I have been helpful
var x = document.getElementsByTagName("div");
for ( var i = 0; i < x.length; i++) {
var y = x[i].innerHTML.indexOf('Second');
if (y>-1) {
x[i].setAttribute("class", "check");
}
}

Need to filter entire div content instead of just part of it

I have a script that filters content based on a string. However, it has to be that exact string and I can't figure out how to filter for a segment of the search string.
ex. If this worked there would be two results with the word "Pokemon"
let divs = document.getElementsByClassName('test');
for (let x = 0; x < divs.length; x++) {
let div = divs[x];
let content = div.innerHTML.trim();
if (content !== 'Pokemon') {
div.style.display = 'none';
}
}
<div class="test">
Pokemon
</div>
<div class="test">
Handtekening
</div>
<div class="test">
Thuis
</div>
Simply use String.prototype.indexOf method and check that the return value equals -1 instead of using !==
const hideElsIfNot = str => {
let divs = document.getElementsByClassName('test');
for (let x = 0; x < divs.length; x++) {
let div = divs[x];
let content = div.innerHTML.trim();
if (content.indexOf(str) === -1) {
div.style.display = 'none';
}
}
};
hideElsIfNot('Pokemon');
<div class='test'>Pokemon</div>
<div class='test'>Digimon</div>
<div class='test'>Not Pokemon</div>
You can see from the example that any divs that contain the string "Pokemon" will not be hidden.

appendChild not working on divs in a loop

I am trying to append new div elements to existing divs by using document.getElementsByTagName("div"), converting it to an array, then using appendChild on it. However, when I inspect the frame source of this jsfiddle, it doesn't seem to append it to the divs. It is just:
<body>
<div id="1">
<div id="2">
test
</div>
</div>
Instead of the expected result:
<body>
<div id="1">
<div id="2">
test
</div><div></div>
</div><div></div>
https://jsfiddle.net/ng58e87w/
var allDivs = [].slice.call(document.getElementsByTagName("div"));
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
allDivs[i].appendChild(newDiv);
console.log(allDivs[i]);
}
I can't comment, but I believe you are just creating empty divs and adding nothing to them. They show up created when you inspect element in the jsfiddle. I also set their text to something and it seemed to work.
var allDivs = [].slice.call(document.getElementsByTagName("div"));
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
newDiv.innerHTML = "Hidden Div?";
allDivs[i].appendChild(newDiv);
console.log(allDivs[i]);
}
Use .after() instead of .appendChild().
var words = ['apple','banana','cake'];
console.log(words[0]);
object1 = {
name:'frank',
greet:function(){
alert('hello '+this.name)
}
};
object2 = {
name:'andy'
};
// Note that object2 has no greet method.
// But we may "borrow" from object1:
object1.greet.call(object2);
/*
var divs = [];
var arr = Array.prototype.slice.call( document.getElementsByTagName("div") );
for(var i = 0; i < arr.length; i++) {
//do something to each div like
var div = document.createElement("div");
arr[i].appendChild(div);
}
*/
var allDivs = [].slice.call(document.getElementsByTagName("div"));
for (var i = 0; i < allDivs.length; i++) {
var newDiv = document.createElement("div");
allDivs[i].after(newDiv);
console.log(allDivs[i]);
}
<div id="1">
<div id="2">
test
</div>
</div>

JavaScript: Append content as child of nextSibling

I'm trying append to the next element of multiple divs. So far I have this:
HTML
<pre data-color="blue"></pre>
<div class="yellow></div>
<pre data-color="blue"></pre>
<div class="yellow></div>
<pre data-color="blue"></pre>
<div class="yellow></div>
After the function runs, the content should look like this:
<pre data-color="blue"></pre>
<div class="yellow><p class="content">My content</p></div>
<pre data-color="blue"></pre>
<div class="yellow><p class="content">My content</p></div>
<pre data-color="blue"></pre>
<div class="yellow><p class="content">My content</p></div>
This is my function thus far:
var blue = document.querySelectorAll("[data-color='blue']");
var next = blue.nextSibling;
for (var i=blue.length; i--;) {
var insertdiv = document.createElement('p');
insertdiv.className = 'content';
insertdiv.textContent = 'My Content';
next[i].parentNode.appendChild(insertdiv, blue[i]);
}
Can't get this to work properly though.
No jQuery please.
querySelectorAll returns a list of elements. That list doesn't have a nextSibling property, so your second line gives you undefined in next.
var blues, i, insertDiv;
blues = document.querySelectorAll("[data-color='blue']");
for (i = 0; i < blues.length; ++i) {
if (blues[i].nextSibling) {
console.log(blues[i].nextElementSibling.tagName);
insertDiv = document.createElement('p');
insertDiv.className = 'content';
insertDiv.textContent = 'My Content';
blues[i].nextElementSibling.appendChild(insertDiv);
}
}
There as several logical errors in your code. #T.J. Crowder has described them perfectly.
However, in your case I would rather use CSS next sibling selector in querySelectorAll:
var next = document.querySelectorAll("[data-color='blue'] + *");
for (var i = 0, len = next.length; i < len; i++) {
var insertdiv = document.createElement('p');
insertdiv.className = 'content';
insertdiv.textContent = 'My Content';
next[i].appendChild(insertdiv);
}
DEMO: http://jsfiddle.net/8uywP/
Why don't you just add them to the .yellow divs? Like this:
var yellow = document.getElementsByClassName("yellow");
for (var i=0, l = yellow.length; i<l; i++) {
var insertdiv = document.createElement('p');
insertdiv.className = 'content';
insertdiv.textContent = 'My Content';
yellow[i].appendChild(insertdiv);
}
Working Fiddle example
There is no need to "Traverse" the dom like that if you have a class available on the elements you need.

Instantiate new element class using javascript

How can I instantiate an existing div element using javascript? Lets say I have:
<div class="container">
<div class="myclass">TROLL FACE</div>
</div>
I want to create as many 'myclass' element inside the 'container' class as I want using javascript. How can I do this?
Please help, thanks.
You may want the .clone method.
var ele = $('.myclass');
for (var i = 0; i < 5; i++) {
ele.clone().appendTo('.container');
}
The live demo.
var container = $('.container');
for (var i = 0; i < 5; i++) {
container.append('<div class="myclass">TROLL FACE</div>');
}
You could use the .append() method.
With or without JQuery:
for (var i = 0; i < howMany; ++i) {
// pure js
var div = document.createElement('div')
div.classList.add('myclass')
somePlace.appendChild(div)
// jquery
$("<div></div>").addClass('myclass').appendTo(somePlace)
}
Try this
<div class="container">
<div class="myclass">TROLL FACE</div>
</div>
var $container = $('.container');
var $myclass = $('.container').html();
var mycount ; // Your count
for(var i =0;i< mycount ; i++){
$container.append($myclass)
}

Categories

Resources