An example of jQuery's problem in determining whether an element exists _ jquery-js tutorial

Source: Internet
Author: User
This article mainly discusses the question about jQuery's determination of whether the element exists. For more information, see this article. Recently, when I was training jQuery, I encountered a problem when jQuery was trying to determine whether the element exists.

The question is as follows: add Id = rad4 after "select button 3". The selected HTML control is followed by the text "select button 4, can be added only once (use js native or JQuery for free)

Function addradio () {if (! Document. getElementById ("rad4") {var main = document. getElementById ("radioContainer"); var input = document. createElement ("input"); input. setAttribute ("type", "radio"); input. setAttribute ("id", "rad4"); var span = document. createElement ("span"); var txt = document. createTextNode ("select button 4"); span. appendChild (txt); main. appendChild (input); main. appendChild (span );}}

It is enough to judge whether an object exists. If (! Document. getElementById ("rad4") But if (! $ ("# Rad4") is a treasure building that is similar to javascript.

In jQuery. Once encapsulated by the $ ("") wrapper, an object is not null or undefined! $ ("# Rad4 ")

Always false. The correct method is as follows:

If no object exists in the package, the length is 0. You only need to do so.

$ (Function () {$ (". domtree p: eq (6) input: eq (1 )"). click (function () {if ($ ("# rad4 "). length <1) {$ ("Select the button 4 "). appendTo ($ (" # radioContainer "));}})})

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.