4

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.

dangerChihuahua007
  • 20,299
  • 35
  • 117
  • 206
  • You might like to look at: http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery edit: in fact, this question is basically a duplicate of that one. Should it be marked as such? – Jeff Jan 15 '12 at 23:49

6 Answers6

8

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

jfriend00
  • 683,504
  • 96
  • 985
  • 979
Flo
  • 1,965
  • 11
  • 18
3

Check the length of the jQuery object.

var element = $('#someElement');
if (element.length) {
    var element_top = element.offset().top;
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

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

jfriend00
  • 683,504
  • 96
  • 985
  • 979
Adaz
  • 1,627
  • 12
  • 14
1

try this:

if($('#someElement').length>0){
   var d = $('#someElement').offset().top;
}
falinsky
  • 7,229
  • 3
  • 32
  • 56
1

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

var d = $('#someElement').offset();
if (d) {
    d = d.top;
}
David Hellsing
  • 106,495
  • 44
  • 176
  • 212
1

Do not use jQuery for that! Use getElementById, since if the element is not in the DOM, the result will be null.

if (document.getElementById("someElement")) {

}
phs
  • 10,687
  • 4
  • 58
  • 84
Garrett
  • 2,936
  • 1
  • 20
  • 22