anon
anon

Reputation:

check if there is a div with a certain id

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

Upvotes: 1

Views: 7127

Answers (4)

Šime Vidas
Šime Vidas

Reputation: 185933

I'd go with:

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

Upvotes: 3

Mark S.
Mark S.

Reputation: 1546

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

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

Upvotes: 0

Richard H
Richard H

Reputation: 39055

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

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

Upvotes: 2

Shadow Wizard
Shadow Wizard

Reputation: 66389

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.

Upvotes: 5

Related Questions