That is my example of problem
<div onclick="this.childNodes(0).innerHTML='0';">
1<b>2</b>3<b>4</b>5
</div>
as you see, two childnodes (" " and " ") are tagged, others are simple text. ”和“ ”),其他是简单文本。 The question is how to change innerHTML of tagged and untagged nodes (texts) in sertain div container without touching other nodes/texts?
Essentially, you'll use the data
(text) property for text nodes ( nodeType
3) and innerHTML
otherwise ( fiddle ):
<div onclick="this.childNodes[0][this.childNodes[0].nodeType === 3 ? 'data' : 'innerHTML'] = '0'">
1<b>2</b>3<b>4</b>5
</div>
[edit] I'm getting really tired of everyone offering libraries as solutions when all that's required is a simple explanation of a basic concept, eg: text-nodes and element nodes have differing content properties, ie: data
and innerHTML
.
I wrote a lib called Linguigi . It would be as easy as
new Linguigi(element).eachText(function(text) {
if(this.parentNode.tagName === 'B') {
return "BACON";
}
});
which turns the text of all text nodes inside b-tags to "BACON". You get the original content as "text" parameter and could transform that.
BTW: You should get rid of the inline event handling ( onclick
attribute)
You can cycle through each of the nodes recursively, checking their nodeType
property in turn and updating the nodeValue
property with '0' if the node is a text node (indicated by nodeType == 3
).
Assuming you have this HTML :
<div onclick="doReplace(this)">
1<b>2</b>3<b>4</b>5
</div>
You can then write a simple replace function that calls itself recursively, like so:
window.doReplace = function (rootNode) {
var children = rootNode.childNodes;
for(var i = 0; i < children.length; i++) {
var aChild = children[i];
if(aChild.nodeType == 3) {
aChild.nodeValue = '0';
}
else {
doReplace(aChild);
}
}
}
A working fiddle can be found here: http://jsfiddle.net/p9YCn/1/
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.