Reputation: 44852
How do I check using javascript if the page I'm on contains a particular div... e.g turtles
Upvotes: 11
Views: 16749
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
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
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