简体   繁体   中英

Get all text contents of a DOM element outside its children using Javascript

I have a DOM element that has some number of children, interleaved by text strings. I want to get each of these text strings, and replace them using regex. For example:

<div>Text started.
<a>Link child inside</a>
Some more text. 
<u>Another child</u>
Closing text.</div>

In this example, I want to extract the strings "Text started.", "Some more text.", and "Closing text.", so that I can replace each of them later with something else.

The solution should be generic since the number of children inside the parent can vary, and the node types as well.

Anyone got a clever answer to achieve this easily using javascript?

You can use childNodes to check if the nodeType is a text node. Doing this inside a forEach you can easily replace the text with whatever you want.

Example:

 var div = document.getElementsByTagName('div').item(0); [].slice.call(div.childNodes).forEach(function(node , i) { if(node.nodeType === 3) { var currNode = div.childNodes[i]; var currText = div.childNodes[i].textContent; currNode.textContent = currText.replace(/text/i, ' Foo'); } }) 
 <div> Text started. <a>Link child inside</a> Some more text. <u>Another child</u> Closing text. </div> 

You can do as follows;

 var textNodes = [...test.childNodes].filter(child => child.nodeType === Node.TEXT_NODE) textNodes.forEach(tn => console.log(tn.textContent)) 
 <div id="test">Text started. <a>Link child inside</a> Some more text. <u>Another child</u> Closing text.</div> 

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