0

I have a div that have multiple p tags. I want to get the text of the p element that is not empty. For example

<div>
 <p></p>
 <p></p>
 <p>data</p>
 <span>some</span>
</div>

I want to get data of third p element that is data.

I can use

document.querySelector("p:nth-child(1)");

but in above case I have to define the child no. But how can I get the p based on empty condition

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Sunil Garg
  • 14,608
  • 25
  • 132
  • 189

1 Answers1

2

Assuming whitespace won't be an issue, you can use the :not() pseudo-class in conjunction with the :empty pseudo-class:

document.querySelector("p:not(:empty)");

Since you are using document.querySelector(), this ensures only the first such element is matched. You cannot express "the first p:not(:empty)" in terms of selectors (i.e. within the selector string itself).

(Of course, you'll probably want to make your selector more specific, unless you really are interested in the first non-empty p element across the entire document.)

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • but if there is any other tag in p tag iteself, then p tag is not considerd as empty.. – Sunil Garg Apr 25 '17 at 10:02
  • @Sunil Garg: Of course you didn't bother mentioning that in your question - all you did was show two empty paragraphs. Well, then you have no choice but to select all of them and iterate until you find one that has no child nodes. – BoltClock Apr 25 '17 at 10:15
  • ok thanks.. can you answer this https://stackoverflow.com/questions/43607844/is-there-any-way-to-get-the-text-data-of-first-non-empty-element-using-query-sel – Sunil Garg Apr 25 '17 at 10:17
  • @Sunil Garg: Can I trust that you haven't left out any crucial details in that other question? – BoltClock Apr 25 '17 at 10:18