Get text from p, not including span values, using Document.querySelector

Viewed 936

I have this element structure.

<p>
  <span class="ts-aria-only">
  Departure
  </span>
  RUH
  <span class="ts-aria-only">&nbsp;Riyadh</span>
</p>

I'm trying to get the text RUH, but using innerText will return the whole text including the value inside <span>.

Some answers posted here on SO uses ajax, which is not applicable for my use case.

2 Answers

It's a text node, so it can't be selected with a query string. You'll have to start from its parent element and access the appropriate childNodes index:

console.log(
  document.querySelector('p').childNodes[2].textContent.trim()
);
<p>
  <span class="ts-aria-only">
  Departure
  </span>
  RUH
  <span class="ts-aria-only">&nbsp;Riyadh</span>
</p>

this should work

Array.from(document.querySelector('p').childNodes).reduce((a,b) => a += b.nodeType==3 ? b.textContent.trim() : '' ,'')

basically you need to check each childNode if it is textNode (nodeType==3) then you could do with it whatever you want

Related