I'm trying to make a script which will change the content of every occurence like this:
<div id="random numbers">
<div class="column-1"></div>
<div class="column-1"><a href="...">this value I want to change</a></div>
<div class="column-1"></div>
</div>
there's many of those^
so far, this is the code I'm trying to make use of:
var elements = document.querySelectorAll('column-1');
for ( var i=elements.length; i--; ) {
elements[ i ].InnerHTML = "test";
}
but this isn't working, and I'm really just trying to piece together some code that will replace the content of the #2 column-1 of every <div id="random numbers">
I appreciate any help here, thanks in advance
There are two problems with your above code. First, your .querySelectorAll()
should be targeting the class ; you need to specify the full stop. Second, the i
in .innerHTML
needs to be lowercase.
After these two bugs have been fixed, you can only apply the change to every second element by running a condition based on a modulo of 2 using i % 2
as follows:
var elements = document.querySelectorAll('.column-1'); for (var i = 0; i < elements.length; i++) { if (i % 2) { elements[i].innerHTML = "OVERRIDDEN"; } }
<div id="random numbers"> <div class="column-1">Should STAY</div> <div class="column-1"><a href="...">Should CHANGE</a></div> <div class="column-1">Should STAY</div> </div>
If you're specifically trying to target the <a>
tags, you can do that directly with querySelectorAll('.column-1 a')
itself, using .outerHTML
if you want to replace the <a>
tag itself. Note that this doesn't require a conditional:
var elements = document.querySelectorAll('.column-1 a'); for (var i = 0; i < elements.length; i++) { elements[i].outerHTML = "OVERRIDDEN"; }
<div id="random numbers"> <div class="column-1">Should STAY</div> <div class="column-1"><a href="...">Should CHANGE</a></div> <div class="column-1">Should STAY</div> </div>
Hope this helps! :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.