Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using querySelector() to exclude descendent

Tags:

javascript

dom

I'm looking to try and do a querySelector for text that avoids picking up a div within the content. Any thoughts gratefully appreciated.

JS

domdoc.querySelector('li.list_item').textContent

HTML:

<li class="list_item">
  Hello
  <a>
    world,
    <div id="tooltip">
      Please ignore this
    </div>
  </a>
  how are you
</li>

Returns:

Hello world, Please ignore this how are you

Would like to see:

Hello world, how are you
like image 564
DrMikey Avatar asked Jul 11 '26 06:07

DrMikey


1 Answers

querySelector will select an element, not an element and its descendants.

textContent including descendants of the list item is a feature of textContent, not of querySelector.

You can clone the list item, remove the div from it, then get the textContent of that.

var li = document.querySelector('li.list_item');
var duplicate = li.cloneNode(true);
duplicate.querySelector("div").remove();
console.log(duplicate.textContent);
<ul>
  <li class="list_item">
    Hello
    <a>
    world,
    <div id="tooltip">
      Please ignore this
    </div>
  </a> how are you
  </li>
</ul>
like image 189
Quentin Avatar answered Jul 13 '26 19:07

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!