Kashyap Kashyap - 3 months ago 8
HTML Question

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?

Answer

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>