简体   繁体   中英

Comparing DOM elements with jQuery

I am working inside of a jQuery each iterator:

$('p').each(function(){ ... });

I'd like to create an expression that evaluates to true when:

  • $(this) is the last p element
  • scope is $(this).parent()
  • $(this) must be a direct child of $(this).parent()
  • $(this) is not necessarily the last direct child of $(this).parent()

Here are a few scenarios, with the desired p marked by asterisks:

<div>
  <p>div1 p1</p>
  <p>div1 p2</p>
  <p>div1 p3***</p>
</div>

<div>
  <p>div2 p1***</p>
  <span>div2 s1</span>
</div>

<div>
  <p>div3 p1***</p>
  <div>
    div3 d1
    <p>div3 p2</p>
  </div>
</div>

I'd post my attempts at a solution, but there have been too many failed ones. Thanks for the help.

You could use a selector such as this:

$('body > div').each(function() {
    $(this).children('p:last').each(function() { /* ... */ });
});

which would return all your wanted <p> tags.

Here is a demo: http://jsbin.com/orage | See Source


Your original requirements does not make any sense.

$(this) must be a direct child of $(this).parent()

$(this) is ALWAYS a direct child of $(this).parent() by definition of what parent() does.

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