Several Methods for jQuery to obtain sibling Elements

Source: Internet
Author: User

JQuery provides several methods to obtain sibling elements.

When obtaining the sibling element of a specified element, you can use adjacent sibling combinator (+), where both sides of the content of + are selector expressions.
If you want to obtain the direct brother element h2 of all h1 in the following example

<div> 

Can be used directly

$('h1 + h2') // Select ALL h2 elements that are adjacent siblings of H1 elements.

 

If you want to filter out the sibling elements of h1, you can also use

$('h1').siblings('h2,h3,p'); // Select all H2, H3, and P elements that are siblings of H1 elements.

Www.jbxue.com

To obtain all the sibling elements after the current element, you can use nextAll ()
For example, for the following html code

<ul> <li>First item</li> <li class="selected">Second Item</li> <li>Third item</li> <li>Fourth item</li> <li>Fifth item</li> </ul>

 

To obtain all the li elements after the second entry, use the following code:
$ ('Li. selected'). nextAll ('lil ');

In the preceding example, general sibling combinator (~) can also be used (~) To achieve
$ ('Li. selected ~ Li ');

You can directly use next () without using selector to obtain the direct sibling element ().

var topHeaders = $('h1'); topHeaders.next('h2').css('margin', '0);

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.