To check if an element with a specific ID exists in the DOM using jQuery, you can use the #
character followed by the ID value as a selector. By checking the length
property of the selected element, you can determine if the element exists or not.
if ($('#myElementId').length) {
// The element exists
} else {
// The element does not exist
}
jQuery checks if id exists example
Simple example code checks if an element with a specific ID exists:
<!DOCTYPE html>
<html>
<head>
<title>jQuery Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="myElementId">Hello, World!</div>
<script>
$(document).ready(function() {
if ($('#myElementId').length) {
console.log('The element exists');
} else {
console.log('The element does not exist');
}
});
</script>
</body>
</html>
Output:
Another example
<!DOCTYPE html>
<html>
<head>
<title>jQuery Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>jQuery check if an element exists</h1>
<div id="div1">
<b>This is a DIV element with an ID of "div1"</b>
</div>
<br>
<br>
<br>
<button id="buttonDiv1">Check if div1 exists</button>
<button id="buttonDiv2">Check if div2 exists</button>
<script>
$(function() {
$('#buttonDiv1').click(function() {
if ($('#div1').length) {
alert('div1 exists');
} else {
alert('div1 does not exist');
}
});
$('#buttonDiv2').click(function() {
if ($('#div2').length) {
alert('div2 exists');
} else {
alert('div2 does not exist');
}
});
});
</script>
</body>
</html>
Do comment if you have any doubts or suggestions on this HTML code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version