Airman
Airman

Reputation: 130

Javascript error on href getElementById when null

I have a popup that lets the user change a href if set or not. If not set, I display "optional web link" as field title. However, I'm getting a JavaScript error on the "if" line that href is null. How can I get href or test it without the error getting in the way? In this application href will be null at times so I need my script to deal with it somehow.

if (document.getElementById('sidebarhref-'+id).href == '') {
    var href = document.getElementById('sidebarhref-'+id).href;
} else {
    var href = 'optional web link';
}

Upvotes: 0

Views: 205

Answers (1)

Quentin
Quentin

Reputation: 944013

Test if the return value of getElementById is a true value before trying to access properties of it.

var element = document.getElementById('sidebarhref-'+id);
if (element && element.href === "") {
// etc

Upvotes: 2

Related Questions