Alex
Alex

Reputation: 41

how to get the text content of an element with no ID in javascript

I want to get a particular text content of the heading element which does not have any ID associated with it. What javascript code should I use to get the content 'I only want this one'.

var elements = document.querySelectorAll('.one span');
console.log(elements[0].text);

This code is not giving the desired output

<h5 class="one two three four">
<span class="s1 s2">I don't want this</span>
I only want this one</h5>

I expect the output to be 'I only want this one', but I am getting undefined...

Upvotes: 1

Views: 112

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370619

You're looking to select the text node, which is not an element, so you can't select it immediately with querySelectorAll (or querySelector) - so, first select the parent (the .one), then navigate to its last child:

const parent = document.querySelector('.one');
const textNode = parent.lastChild;
console.log(textNode.textContent);
<h5 class="one two three four">
  <span class="s1 s2">I don't want this</span>
I only want this one</h5>

Note that if you just want the first element which matches a particular selector string, it's more appropriate to use querySelector (which returns that element), rather than querySelectorAll (which returns a collection, from which you must proceed to select the first element in it).

Upvotes: 2

Related Questions