简体   繁体   中英

Remove characters from an element while using appendChild

I'm trying to remove or replace characters in an element while using appendChild as follow:

var options = from.getElementsByTagName("option");

var to = document.getElementById("target");

to.appendChild(options[i].replace("(A)",""));

I tried various different syntax but no luck. Can someone help? Either JQuery or javascript works for me.

Thanks

I assume you're already in a for loop. If so, use the .text property of the option element, and create a new text node.

to.appendChild(document.createTextNode(options[i].text.replace("(A)","")));

Or better, in the loop append to a string, and create a single node at the end.

var txt = "":
for (var i = 0; i < options.length; ++i)
    txt += options[i].text.replace("(A)"), "");
}
to.appendChild(document.createTextNode(txt));

If you actually wanted to append a copy of the element itself, then use .cloneNode(true) instead.

for (var i = 0; i < options.length; ++i) {
    var clone = to.appendChild(options[i].cloneNode(true));
    clone.text = clone.text.replace("(A)", "");
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM