How to check if an element with a specific id exists on a page in jQuery?

In jQuery, I wrote a piece of code that appears on every page of my site.

var d = $('#someElement').offset().top; 

However, not every page of my site has an element with the identifier "someElement". Unfortunately, jQuery code does not work on these pages that lack such an element.

To solve this problem, I want to check if the element on the page really has the identifier "someElement", and then only runs the code snippet, if any.

How to run this test? Will this test solve the problem? Thanks.

+4
source share
7 answers

$('#someElement').length will return 1 if the element exists, 0 otherwise.

+8
source

Check the length of the jQuery object.

 var element = $('#someElement'); if (element.length) { var element_top = element.offset().top; } 
+3
source

Use if statemtent: if ($('#someElement').length) { do something }

+1
source

try the following:

 if($('#someElement').length>0){ var d = $('#someElement').offset().top; } 
+1
source

Just an alternative way to solve it: you can run var d = $('#someElement').offset() without causing an error (it will just return null), even if this element does not exist. So try:

 var d = $('#someElement').offset(); if (d) { d = d.top; } 
+1
source

Do not use jQuery for this! Use getElementById , because if the item is not in the DOM, the result will be null .

 if (document.getElementById("someElement")) { } 
+1
source

Use the .length property of the jQuery collection returned by your selector:

 if ( $( "#myDiv" ).length ) { $( "#myDiv" ).show(); } 

Note that it is not always necessary to check if an element exists. The following code will show the element if it exists and does nothing (without errors) if it is not:

 $( "#myDiv" ).show(); 
0
source

Source: https://habr.com/ru/post/1391169/


All Articles