Company Blog
Detecting elements in jQuery
January 25, 2012The way I generally use to detect if an element exists is to use the size() method. The following code snippet determine's how many div tags exist on our page:
<script type="text/javascript">
$(document).ready(function() {
$(function() {
var numDivs = $("div").size();
console.log(numDivs);
});
});
</script>
<div class="test">first div</div>
<div>second div</div>
$(document).ready(function() {
$(function() {
var numDivs = $("div").size();
console.log(numDivs);
});
});
</script>
<div class="test">first div</div>
<div>second div</div>
The div's are displayed on the screen and our jQuery function stores the number of div tags in the "numDivs" variable, which outputs to our log. You can also test by an element's class or ID. We can change our "numDivs" variable assignment to look for all div's with a "test" class like this:
var numDivs = $("div.test").size();
To put this to use, we could test for element detection, then do something if the element exists, like this:
var numDivs = $("div.test").size();
if (numDivs > 0) {
do stuff...
}
if (numDivs > 0) {
do stuff...
}
Happy coding!