An example of jQuery's problem in determining whether an element exists
This is the case. During jQuery training recently, jQuery encountered a problem when determining 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("Choose the 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 div: eq (6) input: eq (1)"). click (function ()
{
if ($ ("# rad4"). length <1)
{
$ ("<input type = 'radio' id = 'rad4'> <span> Select button 4 </ span>"). appendTo ($ ("# radioContainer"));
}
}
)
}
Jquery determines whether an element exists
If ($ ("# aaa"). length = 0) alert ("nonexistent ")
Jquery determines whether an element exists
// Determine whether the element if ($ ("# ID") with a specific id value exists "). length> 0) {alert ("exist");} else {alert ("not exist ");} // determine whether a specific label element if ($ ("tag name (such as label)") exists )"). length> 0) {alert ("exist");} else {alert ("not exist ");} // determine whether an element has an if ($ ("# element ID "). find ("ID to be determined "). length> 0) {alert ("exist");} else {alert ("not exist ");}