Code used to determine whether an Id exists under Jquery

Source: Internet
Author: User

1. determine whether an object exists

If the following jQuery code is used to determine whether an object exists, it cannot be used.

If ($ ("# id ")){
} Else {}

Because $ ("# id") returns an object regardless of whether the object exists.

Correct use:

If ($ ("# id"). length> 0) {} else {}

Use the length attribute of the jQuery object to determine whether it exists if it is greater than 0.

Or
If ($ ("# id") [0]) {} else {}

Or you can directly use the native Javascript code to determine:

If (document. getElementById ("id") {} else {}

2. Search for Child Nodes Based on the parent node

JQuery children () returns the byte point of the matched object
Children () returns the Child point of the matched object.
<P> one </p>
<Div id = "ch">
<Span> two </span>
</Div>
JQuery code and functions:
Function jq (){
Alert({{ch}}.children({.html ());
}
$ ("# Ch"). children (). The result of the object [<span> two </span>. .html () is "two"

3. Search for the parent node based on the child node

<Div id = "ch">
<Span> two </span>
<Span id = "sp"> three </span>
</Div>

JQuery code and functions
Jquery. ready ({
Alert({{ch}}.children({?sp=}.html ());
});
$ ("# Ch"). children () Get the object [<span> two </span> <span id = "sp"> three </span>].
$ ("# Ch"). children ("# sp") filter to [<span id = "sp"> three </span>]

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.