How to change innerHTML childNodes in case some children are without tags?

This is my example problem.

<div onclick="this.childNodes(0).innerHTML='0';"> 1<b>2</b>3<b>4</b>5 </div> 

as you can see, two children are marked (" 2 " and " 4 "), the others are plain text. The question is how to change the innerHTML of labeled and unmarked nodes (texts) in a specific div container without touching other nodes / texts?

+4
source share
3 answers

Essentially, you will 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 am very tired of all those who offer libraries as solutions, when all that is required is a simple explanation of the basic concept, for example: text nodes and element nodes have different content properties, that is: data and innerHTML .

+6
source

I wrote a lib called Linguigi . It would be as simple 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 into "BACON". You get the original content as a text parameter and you can convert it.

http://jsfiddle.net/Kz2jX/

BTW: you have to get rid of inline event processing ( onclick )

+1
source

You can cycle through each of the nodes, checking their nodeType property in turn and updating the nodeValue property with "0" if node is the 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> 

Then you can write a simple replacement function that calls itself recursively, for example:

 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 script can be found here: http://jsfiddle.net/p9YCn/1/

+1
source

Source: https://habr.com/ru/post/1438475/


All Articles