JQuery - If ( $('#products').existOn.(document) ) == true { //do this }
How can I ma开发者_Python百科ke this conditional branch.. If the with the ID products is in the HTML code? If #products does exist in the actual document?
Thank you for your response!
Pseudo Javascript (JQuery)
If ( $('#products').existOn.(document) ) == true {
//do this
}
Use length
:
if ( $('#products').length > 0){
// element is present
}
If you want to vary the document
part, you'd do something like this:
if( $(document).find('#products').length > 0 ) {
// do this
}
If it'll always be document
, it'll suffice to do
if( $('#products').length > 0 ) {
// do this
}
An alternative approach of achieving the first example would be to pass a context parameter as a second argument:
if( $('#products', document).length > 0 ) {
// do this
}
Note that the context parameter should be a DOM node, not a jQuery object.
Why bother with jQuery?
if (document.getElementById('products')) {
//do this
}
精彩评论