Dstjohniii Dstjohniii - 4 months ago 9
HTML Question

JS, using replace on every label in a form

So i am trying to do a replace on all the labels in my form when it loads in JS but having no luck.

$(document).ready(function($){
$('.label').each(function(e){
document.getElementById($(this)).textContent = document.getElementById($(this)).innerHTML.replace("and", "&");
}
}


and idk whats better .innerHTML or .textContent they seem to achieve my same goal.
Thanks in advance.

Answer

First of all,m I personally use innerHTML. You don't need to both use

document.getElementById();

and

$(this) 

Try this inside your loop:

var toReplace=$(this).innerHTML;
toReplace.replace("and", "&");

However, note that

document.getElementById("x");

will only grab the first element with ID "x", if you're looking to grab multiple elements, give them all the same class name, then grab them into an array with

myElements=document.getElementsByClassName("classname");

and then iterate through them to replace like this:

for (i=0; i<myElements.length, i++){
    myElements[i].innerHTML.replace('and', '&');
}