To check if a div
element exists using jQuery, you can use the length
property to determine if any elements in the DOM match the selector.
HTML:
<div id="myDiv">This is a div element</div>
JavaScript:
// Check if the div element with ID 'myDiv' exists
if ($('#myDiv').length) {
// If the element exists, change its background color to yellow
$('#myDiv').css('background-color', 'yellow');
} else {
// If the element does not exist
console.log("Error: The 'myDiv' element does not exist.");
}
The script checks if the div
element with ID myDiv
exists in the DOM using the jQuery selector $('#myDiv')
. If the element exists, its background color is changed to yellow using the css()
method. If the element does not exist, an error message is displayed in the console using the console.log()
method.
Check if div exists jQuery example
Simple example code of how you can use jQuery to check if a div
element exists in the DOM and performs some action based on its existence.
<!DOCTYPE html>
<html>
<head>
<title>Check if div element exists with jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="myDiv">This is a div element</div>
<script>
$(document).ready(function() {
if ($('#myDiv').length) {
$('#myDiv').css('background-color', 'yellow');
} else {
console.log("Error: The 'myDiv' element does not exist.");
}
});
</script>
</body>
</html>
Output:
Do comment if you have any doubts or suggestions on this div code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version