how to find if specific element exists in html

I am trying to stick the ads on website while user scroll it, using the code below

//to Stick Ads while scroll on Desktop
    var StickHead=$('#StickHead').offset().top;
    $(window).scroll(function () {
        if ($(window).scrollTop() > stickyHeaderTop) {
            $('#StickHead').css({ position: 'fixed', top: '0px' });          
        } else {
            $('#StickHead').css({ position: 'static', top: '0px' });          

this code work's fine when we have div with id StickHead, but it throws an error when there is no StickHead id, as it would be difficult to copy paste it in selected page I have placed this code in script which is on all pages, now my question how can I make it work in all pages without error?
I have thought it would be easier if I can find if the Id exists, then run this code, otherwise leave it.
I have idea but not able to implement, any help?



Asked by:- Vipin
: 1432 At:- 6/13/2017 7:32:34 AM
jquery javascript html

1 Answers
profileImage Answered by:- vikas_jk

You can use jquery function length() to check if there any element with associated class/div, with code like 

if ($("#ElementId").length == 0) {
        //Element does not exist, if value is greater than 0, element exists
   //.length() gives the size of number of elements associated with particular id/class in html

Check this url fore more details

For your code, you can use this:

//to Stick Ads while scroll on Desktop
    var StickHead= 0;
    if ($("#StickHead").length != 0) {
        StickHead= $('#StickHead').offset().top;       
    $(window).scroll(function () {     
       //in your code i think you are pointing 'StickHead' instead of 'stickyHeaderTop'  
         if ($(window).scrollTop() > StickHead) {       
            $('#StickHead').css({ position: 'fixed', top: '50px' });           
        } else {           
            $('#StickHead').css({ position: 'static', top: '0px' });           

it should work, let me know, thank you

At:- 6/13/2017 2:21:37 PM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly