Home > Web Front-end > JS Tutorial > body text

Several good ways to get sibling elements with jQuery_jquery

WBOY
Release: 2016-05-16 16:46:59
Original
1499 people have browsed it

When getting the sibling elements of a specified element, you can use adjacent sibling combinator ( ), in which both sides of the content are selector expressions.
If you want to get all the direct sibling elements h2 of h1 in the following example

Copy code The code is as follows:


Main title


Section title


Some content...


Section title


More content ...




You can use it directly
Copy code The code is as follows:

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

If To filter the sibling elements of h1, of course you can also use
Copy the code The code is as follows:

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

If you want to get For all sibling elements after the current element, you can use nextAll()
For example, for the following html code
copy the code code As follows:


  • First item

  • Second Item

  • Third item

  • Fourth item

  • Fifth item



If you want to get all li elements after the second entry, you can use the following code
Copy the code The code is as follows:

$('li.selected').nextAll('li');

The above example can also be implemented using general sibling combinator (~)
Copy code The code is as follows:

$('li.selected ~ li');

To obtain direct sibling elements, you can also use next() directly without using selector.
Copy code The code is as follows:

var topHeaders = $('h1');
topHeaders.next('h2').css('margin', '0);
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template