Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery: Check if element exists alongside '.remove()'

Tags:

jquery

exists

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') 
}
like image 221
gavsiu Avatar asked Jul 15 '11 23:07

gavsiu


People also ask

How do you check if an element exists or not in jQuery?

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.

How to remove div content in jQuery?

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.

How remove and append in jQuery?

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.


1 Answers

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
like image 121
gilly3 Avatar answered Sep 30 '22 19:09

gilly3