开发者

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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜