jQuery and Javascript Check the Existence of an Element
Learn how jQuery and Javascript Check the Existence of an Element
Published
- jQuery and Javascript Check the Existence of an Element
- Check the existence of an element in jQuery
- check the existence of an element in JavaScript
- check the existence of an element in JavaScript and jQuery
jQuery and Javascript Check the Existence of an Element
If your goal to execute a block of code if some elements available on page either using Javascript or jQuery is easy to perform with the following code. It can be a requirement when you are dynamically creating elements on a webpage.
Check the existence of an element in jQuery
if ( $(selector).length ) {
//Execute your code
}
check the existence of an element in JavaScript
<script>
if (document.getElementById('result'))
document.getElementById('result').innerHTML = 'Id result exist';
else
console.log ('Id #result does not exist');
if (document.getElementsByTagName('p').length > 0)
document.getElementsByTagName('p')[0].innerHTML = "P tag is available.";
else
console.log("P tag is not available.");
</script>
check the existence of an element in JavaScript and jQuery
<div class="wrapper"></div>
<div id="result"></div>
<p></p>
<script src="https://code.jquery.com/jquery-git.js"></script>
<script>
//using jQery
if ( $(".wrapper").length > 0 ) {
console.log ('wrapper class exist');
}
//using Javascipt
if (document.getElementById('result'))
document.getElementById('result').innerHTML = 'Id result exist';
else
console.log ('Id #result does not exist');
if (document.getElementsByTagName('p').length > 0)
document.getElementsByTagName('p')[0].innerHTML = "P tag is available.";
else
console.log("P tag is not available.");
</script>