How do I check if an element exists if the element is created by .append() method? $('elemId').length doesn't work for me.

 

If you're using jQuery and you want to check if an element exists after it has been created using the .append() method, you should use the .length property along with a selector that matches the appended element correctly. Here's how you can do it with an example:

Suppose you have an HTML structure like this:

html
<div id="container"> <!-- Some existing content --> </div>

And you want to append a new <p> element to the #container element using jQuery:

javascript
$(document).ready(function () { // Append a new <p> element to the #container $('#container').append('<p id="appended">This is an appended element.</p>'); // Check if the appended element exists if ($('#appended').length > 0) { console.log('Appended element exists.'); } else { console.log('Appended element does not exist.'); } });

In this example:

  1. We use the .append() method to add a new <p> element with the id "appended" to the #container element.

  2. After appending, we check if the appended element exists by selecting it with the $('#appended') selector and using .length to check if there are any matching elements.

  3. If the .length property is greater than 0, it means the element exists, and we log "Appended element exists." Otherwise, we log "Appended element does not exist."

Make sure that you execute this code after the element has been appended, typically within a $(document).ready() block to ensure the DOM is fully loaded before manipulating it with jQuery.

Comments