简体   繁体   中英

What do I wrap a document.getElementById so as not to throw a TypeError when ID can't be found?

I'm using the Hammer.js library ( http://hammerjs.github.io/ ) to enable touch gestures in a vanilla javascript environment. After including the library, I have a call that works on my gallery pages. The call fails should the id slide not be found on the page. The resulting TypeError also prevents the other js for the site from being executed. I'm really new to this, but from doing some reading I think I need to wrap this code in a test so it won't run if id slide does not exist. Knowing how to do this will help me fix some other issues with other ids and libraries.

So after the Hammer.js code I have my own code:

var slide = document.getElementById('slide');
var mc = new Hammer(slide);
mc.on("swipeleft", function(ev) {
var url = document.querySelector('a.next').getAttribute('href');
if (url) {
    window.location = url;
}
});

mc.on("swiperight", function(ev) {
var url = document.querySelector('a.prev').getAttribute('href');
if (url) {
    window.location = url;
}
});

How do I prevent this code from executing if the page doesn't contain the id slide? (and when I say it doesn't contain it, I mean that it will not exist on that page, not that the DOM isn't ready.)

Thanks.

Just test for it:

var slide = document.getElementById('slide');

if( slide ){
  // .. your code
}

End the surrounding function execution if slide is falsy:

var slide = document.getElementById('slide');    
if (!slide) return;
//... The rest of your code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM