Swapnil
Swapnil

Reputation: 65

finding p tag between two div tags

I want to find out

tag between two different divs using jQuery. For example

<div class="abc">
    <div class="pqr">
        <h2>Header Two</h2>
            <p>some text</p>
    </div>
</div>
<p>some text 1</p>
<div class="lmn">
      <p> some text </p>
</div>

So I want to find the p with "some text 1". (the text could be anything.)

Can anyone tell me how can I do this ?

Upvotes: 2

Views: 188

Answers (3)

user52889
user52889

Reputation: 1501

The following will find all p tags which have preceding siblings .abc and following siblings .lmn:

$('.abc + p + .lmn').prevUntil('.abc','p')

If you just want ANY p tag between two divs, then do

$('div + p + div').prevUntil('div','p')

Upvotes: 1

SaidbakR
SaidbakR

Reputation: 13544

You can get all p tags in your document and then check if the parent is div tag or not and then get the text of p tag of non parent div as follows:

$(document).ready(function(){     
       $("p").each(function(index){
         if (!$(this).parent().is("div")) alert($(this).text())         
       })     
    })

Checkout this DEMO: http://jsbin.com/sugodawiza/1/

Upvotes: 0

karthikr
karthikr

Reputation: 99620

Here is one way to do it:

Basically, using the + tag, figure out if such a pattern exists, and then retrieve the required content

if($('.abc + p + .lmn').length) { // + matches the elements at the same level
    var x = $('.abc + p').text(); //Now that such a pattern exists , note that it could be multiple, so handle it appropriately, fetch the text
    console.log(x);
}

Here is a fiddle

Upvotes: 2

Related Questions