Find div by inner text and adding class - javascript

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");
}
}

Related

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

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>

Selecting every 2nd div inside other div

<div id="random numbers">
<div class="column-1"></div>
<div class="column-1">this value I want to change</div>
<div class="column-1"></div>
</div>
from earlier advice, I have this code:
var elements = document.querySelectorAll('.column-1 a');
for (var i = 0; i < elements.length; i++) {
elements[i].outerHTML = "OVERRIDDEN";
}
the issue I'm having is that this replaces each <a inside each div <div id="random numbers">), while I would like it only to replace the second column-1 inside each random numbers div.
thank you in advance!
document.querySelectorAll('.column-1 a')[1].outerHTML = "OVERRIDDEN";
Just work with i
var elements = document.querySelectorAll('.column-1');
for (var i = 0; i < elements.length; i++) {
if(i%2) { // override 2nd, 4th, etc.
elements[i].outerHTML = "OVERRIDDEN";
}
}
https://jsfiddle.net/ishukshin/av6t6kxz/

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>

Wrap each span in a container

I am trying to wrap each span in a container. To achieve this I used a for loop to create multiple containers and then append the span to the container of the same index.
Why isnt my logic working?
Html: Two span tags (Sorry html code wont show)
Javascript:
var spans = document.getElementsByTagName('span'),
body = document.getElementsByTagName('body')[0];
for(var i = 0; i < spans.length; i++)
{
var container = document.createElement('figure');
container.setAttribute('class', 'container');
body.appendChild(container);
container.appendChild(spans[i]);
}
Edit: https://jsfiddle.net/tsrLutpg/1/
Part of the reason for the oddity is because the HTMLCollection set to spans is "live." This means, as you modify a <span>, the collection changes to reflect that change.
In this case, the collection changes the order the <span>s are listed in. As you're iterating, some may be wrapped twice moving from one <figure> to another, while others may remain unaltered when they move to an index that's already been visited.
<span>Foo</span>
<span>Bar</span>
<span>Baz</span>
for (var i = 0; i < spans.length; i++)
{
// ...
console.log(Array.from(spans).map(s => s.outerHTML));
container.appendChild(spans[i]);
}
// ["<span>Foo</span>", "<span>Bar</span>", "<span>Baz</span>"] (1 2 3)
// ["<span>Bar</span>", "<span>Baz</span>", "<span>Foo</span>"] (2 3 1)
// ["<span>Bar</span>", "<span>Foo</span>", "<span>Baz</span>"] (2 1 3)
You can avoid this by creating a static collection of the <span>s to iterate over, that doesn't change as the <span>s change.
In modern browsers, you can use Array.from() for this (similar to the above snippet).
var spans = Array.from(document.getElementsByTagName('span'));
https://jsfiddle.net/394La14t/
For compatibility, MDN offers a polyfill you can use. Or, you can call .slice() instead.
var spans = Array.prototype.slice.call(document.getElementsByTagName('span'), 0);
Here is the solution that properly wraps span tags:
var spans = document.getElementsByTagName("span");
for (var i = 0; i < spans.length; i++) {
var container = document.createElement("figure");
container.className = "container";
var span = spans[i];
span = span.parentNode.replaceChild(container, span);
container.appendChild(span);
}
If you're using jQuery library on the page, you could use next line of code:
$("span").wrap("<div class = 'outer'></div>")
Here is an alternative solution using insertBefore, before appendChild:
var containers = [];
var body = document.getElementsByTagName('body')[0];
var spans = document.getElementsByTagName('span');
for (var i = 0; i < spans.length; i++) {
containers[i] = document.createElement('figure');
body.insertBefore(containers[i],spans[i]);
containers[i].appendChild(spans[i]);
}
span {
background-color: rgb(191,191,255);
}
figure {
border: 1px solid rgb(0,0,255);
}
<span>ABC</span>
<span>ABC</span>
<span>ABC</span>
<span>ABC</span>
<span>ABC</span>
<span>ABC</span>
<span>ABC</span>
<span>ABC</span>
<span>ABC</span>
<span>ABC</span>
<span>ABC</span>
Just respect the order of your spans, instead of inserting the container after all of their spans insert it where the old span used to be. Change:
body.appendChild(container);
To:
spans[i].parentNode.insertBefore(container, spans[i]);
And now it works:
var spans = document.getElementsByTagName('span'),
body = document.getElementsByTagName('body')[0];
for(var i = 0; i < spans.length; i++)
{
var container = document.createElement('figure');
container.setAttribute('class', 'container');
spans[i].parentNode.insertBefore(container, spans[i]);
container.appendChild(spans[i]);
}
<span></span>
<span></span>

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