Dstjohniii Dstjohniii - 1 year ago 56
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.getElementById($(this)).textContent = document.getElementById($(this)).innerHTML.replace("and", "&");

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

Answer Source

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




Try this inside your loop:

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

However, note that


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


and then iterate through them to replace like this:

for (i=0; i<myElements.length; i++){
    myElements[i].innerHTML.replace('and', '&');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download