tags:

views:

209

answers:

2

Hi,

I have a div that looks like:

<div id="blah"> <a href="#" >hello</a>   <a href="#"> world</a></div>

I want to disable all the links inside this div using e.preventDefault();

How can I select all href tags that are inside the div id="blah" using jquery?

+2  A: 

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;
    }
Russ Cam
+4  A: 
$('#blah a').click(function(e){ e.preventDefault(); });

Non-jQuery ( I did not test this ):

    var addEvent = (function() {
    function addEventIE(el, ev, fn) {
        return el.attachEvent('on' + ev, function(e) {
     return fn.call(el, e);
        });
    }
    function addEventW3C(el, ev, fn) {
        return el.addEventListener(ev, fn, false);
    }
    return window.addEventListener ? addEventW3C:addEventIE;
    })();

var anchors = document.getElementById('blah').getElementsByTagName('a');
for ( var i = anchors.length; i--; ) {
    addEvent( anchors[i], 'click', function(e) { 
        e = e || window.event;
        if ( e.preventDefault ) e.preventDefault()
        else e.returnValue = false
    });
}
meder
is it possible w/o jquery?
mrblah
updated for non-jQuery
meder