How do i remove the character "," from a div. for example,
<div class="something">This, is, the, text. </div>
Now i want to remove all the ","s from that div using javascript.
Please forgive me for being too noob in javascript.
How do i remove the character "," from a div. for example,
<div class="something">This, is, the, text. </div>
Now i want to remove all the ","s from that div using javascript.
Please forgive me for being too noob in javascript.
var elements = document.getElementsByClassName("something");
elements[0].innerHTML = elements[0].innerHTML.replace(/,/g,'');
Check this example out: http://jsfiddle.net/QpJNZ/
Update:
var elements = document.getElementsByClassName("something");
for (var i = 0; i < elements.length; ++i) {
elements[i].innerHTML = elements[i].innerHTML.replace(/,/g,'');
}
This is how to make this work for more than one element.
Check this example out: http://jsfiddle.net/VBEaQ/2/
If the element only contains text and no other elements, you can simply do get the inner content of the element then perform string replacement:
element.innerHTML = element.innerHTML.replace(/,/g, '');
To replace all occurrences of a character sequence, you have to use a regular expression with the g
lobal modifier.
If the element contains other elements, you can iterate over all child text nodes:
function replace(element, needle, repl) {
var children = element.childNodes, // get a list of child nodes
pattern = new RegExp(needle, 'g'), // prepare pattern
child, i, l;
for(i = 0, l = children.length; i < l; i++) {
child = children[i];
if(child.nodeType === 3) { // if we deal with a text node
child.nodeValue = child.nodeValue.replace(pattern, repl); // replace
}
}
}
Things to watch out for:
If the text you are searching for contains special regular expression characters, you have to properly escape them first.
If you want to replace the text inside child elements as well, you have to call this function recursively for each element node (nodeType
is 1
).
Reference: String.replace
, Node.childNodes
, Node.nodeType
, Node.nodeValue
, RegExp