简体   繁体   中英

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 ?

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

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 div s, then do

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

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM