Alpha
Alpha

Reputation: 14086

Xpath to find out element which has ANY text

I've situation where I can have text in any of the tags(not sure which one is that). Let's take following HTML code snippet for example:

<div .....>
  <div ......>
    <div ......>
       <div ......>

One of the above has text, but not sure which one has it. Let's take following two examples:

In this, div 3 has text:

<div .....>
  <div ......>
    <div ......>Hello
       <div ......>

In this, div 2 has text:

<div .....>
  <div ......>Hi
    <div ......>
       <div ......>

I want to get element for the div which contains ANY text, no matter what it is. Can we write xpath to get an element which has ANY text?

Upvotes: 8

Views: 7366

Answers (3)

and for any element you can use:

<div .....>
  <table .....>
    <tbody.....>
      <tr.....>
        <td.....>
          <span .....>Some text
            <div .....>

//*[normalize-space(text())]

Upvotes: 2

Saifur
Saifur

Reputation: 16201

If you don't want the elements with blank text your selector should be like this

//div[. !='']

Here, . pointing to parent and !='' simply ignoring elements with blank text.

Upvotes: 2

har07
har07

Reputation: 89325

You can get all <div> having direct child non-empty text node(s) like this :

//div[normalize-space(text())]

Upvotes: 13

Related Questions