Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test if an element with a certain ID exists on a page in jQuery?

In jQuery, I have written a piece of code that appears on every page of my website.

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

However, not every page on my website has an element with an ID of "someElement". Unfortunately, on these pages that lack such an element, no jQuery code works.

To solve this problem, I want to test if an element on the page indeed has the ID of "someElement" and then only run the code snippet above if there is.

How do I perform this test? Will this test solve the problem? Thank you.

like image 463
dangerChihuahua007 Avatar asked Dec 07 '22 17:12

dangerChihuahua007


1 Answers

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

like image 93
Flo Avatar answered Dec 10 '22 11:12

Flo