jquery Parents implementation code and description

Source: Internet
Author: User

You can see that the parent is very clear, is the current element of the parents, parents is the ancestor element of the current element. The following examples illustrate:

<div id= ' Div1 ' >
<div id= ' Div2 ' ><p></p></div>
<div id= ' div3 ' class= ' a ' ><p></p></div>
<div id= ' div4 ' ><p></p></div>
</div>

$ (' P '). Parent () takes the div2,div3,div4.
$ (' P '). Parent ('. A ') takes the Div3
$ (' P '). Parent () is Div1, which is strange, but the character of the jquery object itself determines that this is possible.
$ (' P '). Parents () The DIV1,DIV2,DIV3,DIV4 is taken.
$ (' P '). Parents ('. A ') takes the Div3

<!doctype html>
<style>

P, Div, span {margin:2px; padding:1px;}
div {border:2px white solid;}
span {cursor:pointer; font-size:12px;}
. Selected {Color:blue}
b {color:red; display:block; font-size:14px;}
</style>
<script src= "Http://code.jquery.com/jquery-1.4.4.js" ></script>
<body>
<p>
<div>
<div><span>hello</span></div>
<span>hello again</span>

</div>
<div>
<span>and Hello again</span>
</div>
</p>

<b>click hellos to toggle their parents.</b>
<script>
function showparents () {
$ ("div"). CSS Tutorial ("Border-color", "white");
var len = $ ("span.selected")
. Parents ("div")
. CSS ("Border", "2px Red Solid")
. length;
$ ("B"). Text ("Unique div parents:" + len);
}
$ ("span"). Click (function () {
$ (this). Toggleclass ("selected");
Showparents ();
});</script>

</body>

$ ("a"). Parent () will get <p>
$ ("a"). Parents () Gets the parent object as <P><DIV.3><DIV.1>
$ ("a"). Parents (). Filter ("div") will get <div.3><div.1>, and can also be written as $ ("a"). Parents ("div").
If you want to <div.2> objects can be written like this: $ ("a"). Parents ("Div:eq (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.