Use the traditional JavaScript method as follows:
The code is as follows |
Copy Code |
if (document.getElementById (' div ')) { Find the corresponding element } else { No found the corresponding element found } |
Using jquery is a simple matter of determining whether this element is 0 or not, and if 0 is not, the code is as follows:
The code is as follows |
Copy Code |
if ($ ("#div"). Length > 0) { Locate the element that corresponds to Id=div, and then execute this block of code } |
You can even find a combination of elements, such as the following, we find an ID defined as the DIV element contains IMG, the code is as follows:
The code is as follows |
Copy Code |
if ($ ("#div img"). Length > 0) { Locate the element that corresponds to the ID=DIV and contains IMG, and then execute this block of code } |
Cases
Taking ID=ABC as an example
$ (' #abc ') returns the JQuery object (details can refer to the jquery manual) regardless of the presence of ID=ABC elements on the page, so we cannot use if ($ (' #abc ')) to judge.
can use
The code is as follows |
Copy Code |
if ($ ("#abc"). Size () > 0) {} Or if ($ ("#abc"). Length > 0) {} |
Finding child nodes based on parent node
jquery Children () returns the byte point of the matched object
Children () returns the Transposon mediated point of the matched object
The code is as follows |
Copy Code |
<p>one</p> <div id= "ch" > <span>two</span> </div> jquery Code and functionality: function JQ () { Alert ($ ("#ch"). Children (). HTML ()); } $ ("#ch"). Children () |
Get the object [<span>two</span>]. So the result of HTML () is "two"
Finding the parent node based on child nodes
The code is as follows |
Copy Code |
<div id= "ch" > <span>two</span> <span id= "SP" >three</span> </div>
|
jquery Code and functionality
code is as follows |
copy code |
Jquery.ready ({ alert ($ ("#ch"). Children ("#sp"). html ()); }); $ ("#ch"). Children () Gets the object [<span>two</span><span id= sp >three</span>]. $ ("#ch"). Children ("#sp") filtered [<span id= sp >three</span>] |