Accessing the text node of an element - unexpected behavior (for me)

I’m trying to access the text of some elements using jquery, but it seems that once the text is accessed, it is removed from the element so accessing again the same node will return undefined.
The jquery code is like follows:

theText = $("#quotes-content-wrapper").children()[x].childNodes[0];

where x takes values from 0 to $("#quotes-content-wrapper").children().length - 1, depending on which element is clicked.

The HTML part:

<div id="quotes-content-wrapper">
      <p id="q1" class="bot-quote">We believe that South Africa belongs to all the peopl [...]</p>
      <p id="q2" class="bot-quote">I really wanted to retire and rest [...]</p>
      <p id="q3" class="bot-quote">Education is the most powerfu[...].</p>
      <p id="q4" class="bot-quote">To deny people their human rights is to challe[...]</p>
      <p id="q5" class="bot-quote">Our human compassion binds[...]</p>
</div>

.bot-quote has display:none; , in case it matters somehow.

I am able to get the text from each paragraph once, but when I get back to any of them, they don’t have the text content anymore. Is this normal behavior of .children()[x].childNodes[0] ?

Sorry if I haven’t been to clear. Please ask if you don’t understand what I meant.

I think I get what you’re doing but I’m not clear why you’re chaining .children().childNodes to do it, instead of using the :nth-child() Selector and chaining it with .text()

For some reason, it’s not working. It doesn’t return the element needed…

Does it not return an element at all, or does it just return the wrong element? If the latter, it’s important to note that nth-child is a 1-indexed selector as opposed to 0-indexed so that may be the issue

It returns the html as child…Nevermind this. I made it return the right thing eventually. Will look up for a different approach for my problem considering the new info i’ve got.

Yay! I made it work with this new approach. Thanks for reminding me of it!

1 Like