Search code examples
javascriptjqueryselectorsizzle

Select all links and forms without jQuery


How can I select all a and form tags without needing to include jQuery?

I ultimately am trying to do the following:

$("a").click(function {
    window.onbeforeunload = null;
});

$("form").submit(function {
    window.onbeforeunload = null;
});

But I really would rather not include jQuery (or even Sizzle.js), if there's a more compact way to do that.


Solution

  • You can use document.querySelectorAll() like this:

    var els = document.querySelectorAll( 'a' );
    for( var i=els.length; i--; ) {
      els[i].addEventListener( 'click', function(){ window.onbeforeunload = null; } );
    }
    

    Similar for the <form> tags.

    It is available in most modern browsers (caniuse.com).