Skizit
Skizit

Reputation: 44852

Javascript: Check if page contains a particular div

How do I check using javascript if the page I'm on contains a particular div... e.g turtles

Upvotes: 11

Views: 16749

Answers (4)

Elliot B.
Elliot B.

Reputation: 17681

I'd just like to point out that document.contains is another way to do this.

document.contains is particularly useful if you have a web application whose components are rendered virtually before insertion into the DOM.

Upvotes: 1

BiAiB
BiAiB

Reputation: 14132

if you have that div's id, you can do it that way:

var myDiv = document.getElementById( 'turtles' );

if ( myDiv ) {
    //It exists
}

overwise, if it's a class, you'd better use a framework (jQuery here):

if ( $('.turtles').length > 0 ) {
  //it exists
}

Upvotes: 2

Shadow Wizard
Shadow Wizard

Reputation: 66388

Like this:

<script type="text/javascript">
function CheckExists() {
  var oDiv = document.getElementById("turtles");
  if (oDiv) {
    alert("exists");
  }
  else {
    alert("does not exist");
  }
}
</script>

The function must be located in bottom of page or called after page finished loading.

Upvotes: 1

niksvp
niksvp

Reputation: 5563

if(document.getElementById("divid")!=null){
  alert('Div exists')
}

Upvotes: 18

Related Questions