jQuery: how to check if an attribute exists

by Alex Azuero

HTML

<div id="test">ID: #test</div>

JavaScript

// jQuery 1.6.x, 1.7.x, 1.8.x, 1.9.x, 2.x 

var noAttr = $('#test').attr('title'); // undefined

// then...
if(typeof noAttr == 'undefined') { // strict equality comparison doesn't work
    $('#test').attr('title', 'Test');
}