0

I am trying to grab the text inside a div container and perform some logic based upon the text content instead of changing it. I tried to use Node.childNodes but it returns a live Nodelist instead of a copy.

Here is the DOM structure, I am trying to grab text without a container from it only.

<div class="container" > <span >text inside span</span> text without a container <button>text inside button new</button> <button>text inside button</button> </div> 

Any ideas?

EDIT:

Desired Output:

'text without a container' as a string

9
  • 1
    Which is your code? try to use <> for create a complete snippet. can you write the desired output? Commented Mar 23, 2021 at 14:44
  • 1
    Did you do anything with your node list? like loop over it and try something like a .text() ? Commented Mar 23, 2021 at 14:44
  • Does this answer your question? get text of an element without children in javascript Commented Mar 23, 2021 at 14:48
  • @HereticMonkey No, I don't want to use jQuery. Commented Mar 23, 2021 at 14:51
  • @SimoneRossaini I am not sure if my code would help understanding the issue, I have updated the question to include desired output. Commented Mar 23, 2021 at 14:52

1 Answer 1

0

You can use this:

const parent = document.getElementById('parent'); const nodes = parent.childNodes; let text = ""; for (let node of nodes) { if (node.nodeName === '#text') { text += node.textContent.trim(); } } console.log('Final result: ', text);
<div id="parent"> <span>Inside span</span> I'm free! as a bird! <span>I wish I was</span> </div>

This will loop through all of the child nodes and will only extract text that is not within another element.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.