I know you can check if an element exists with $('div').length
, but when an element is destroyed using .remove()
, .length
still reports the div exists. How can I find whether or not it actually exists?
if ($('div').length) {
alert('yes')
} else {
alert('no')
}
There are two ways to check whether an element in the HTML document exists or not using jQuery. Approach 1: Using the length property in jQuery. If the element exists, then the length property will return the total count of the matched elements with the specified selector.
To remove elements and its content, jQuery provides two methods: remove(): It removes the selected element with its child elements. empty(): It removes the child element from the selected elements.
jQuery uses: . append(); and . remove(); functions to accomplish this task. We could use these methods to append string or any other html or XML element and also remove string and other html or XML elements from the document.
By exists, you mean you want to see if it exists in the dom? Check to see if "html" is an ancestor:
var $myDiv = $(".myDiv");
$myDiv.closest("html").length; // returns 1
$myDiv.remove();
$myDiv.closest("html").length; // returns 0
Or use .is("html *")
. It returns a boolean, which is handy:
var $myDiv = $(".myDiv");
$myDiv.is("html *"); // returns true
$myDiv.remove();
$myDiv.is("html *"); // returns false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With