The following will get you all <a>
elements inside <div>
with id blah that have a href
attribute defined.
$('#blah a[href]').click(function(e) { e.preventDefault(); });
without jQuery, something like the following (I've obviously been living in jQuery world far too long as I originally had preventDefault in the vanilla JavaScript. Unfortunately, not cross-browser :( ) I did test this in Firefox, IE and Chrome
var anchors = document.getElementById('blah').getElementsByTagName('a');
for(var i=0; i < anchors.length; i++) {
addEvent(anchors[i], 'click', preventDefault);
}
function preventDefault(e) {
e = e || window.event;
(e.preventDefault)?
e.preventDefault() : e.returnValue = false;
}
function addEvent(obj, evType, fn){
if (obj.addEventListener){
obj.addEventListener(evType, fn, false);
return true;
}
else if (obj.attachEvent){
var r = obj.attachEvent("on"+evType, fn);
return r;
} else {
return false;
}
}
For interest, this is how jQuery implements preventDefault()
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if( !e )
return;
// if preventDefault exists run it on the original event
if (e.preventDefault)
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
e.returnValue = false;
}