admin管理员组

文章数量:1293013

I have a string and I need to check if there is in the page a div with id = to my string.

How can i do this with jquery?

Like:

if (isset $(mystring))
 // do somethinhg

I have a string and I need to check if there is in the page a div with id = to my string.

How can i do this with jquery?

Like:

if (isset $(mystring))
 // do somethinhg
Share Improve this question asked May 13, 2011 at 23:06 anonanon
Add a ment  | 

4 Answers 4

Reset to default 5
if ($("#" + mystring).length > 0)
  alert(mystring + " exists!");
else
  alert("element with id " + mystring + " does not exist..");

Have this code either in the bottom of the page or wrapped inside $(document).ready() function otherwise even if the element exists further in the page it won't be recognized.

I'd go with:

if ( $('#' + mystring)[0] ) {

jQuery is not needed to do this. In native js:

if (document.getElementById("mystring")) {
   alert("exists");
}

You can do this with the is() function. http://api.jquery./is/

Here is a quick example: http://jsfiddle/hRLgw/

本文标签: javascriptcheck if there is a div with a certain idStack Overflow