Dstjohniii Dstjohniii - 4 months ago 7
Javascript Question

Using replace on every label in a form

I'm trying to do a replace on all the labels in my form when it loads in JS, but I'm having no luck.

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


I don't know what's better:
.innerHTML
or
.textContent
. They seem to both achieve my goal.
Thanks in advance.

Answer

First of all, 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', '&');
}
Comments