Search code examples
javascriptjqueryhtmlhyperlinkpreventdefault

Can't select elements with jQuery


I want to prevent a link from taking the user to another page. When I try to select elements with getElementById("id"), it works fine. When I try to select by using $("#id"), however, it doesn't work. To clarify, this works: https://jsfiddle.net/1nwaptL9/

but this doesn't work: https://jsfiddle.net/7vkepm9e/1/

I realise both of these fiddles do actually work, but when I load the HTML files in Chrome, the one with the jQuery selection doesn't work. Since the source code I've included below works fine in JSFiddle, but not in Chrome, I suspect I've done something wrong, but JSFiddle doesn't process links or something like that. Any help would be appreciated!

Source code that doesn't work:

<html>
<body>
<a id="preventlink" href="http://youtube.com"> click here </a>
<script src="js/jquery-1.11.3.min.js"> </script>
</body>
</html>

<script>
var link=$("#preventlink");
link.addEventListener("click", function(e) {
    e.preventDefault()}, false)

    </script>

Solution

  • jQuery creates a jQuery instance, if you want the actual DOM element, you can do the following:

    var link = $("#preventlink")[0];
    

    Or, just keep using jQuery to add events:

    $("#preventlink")
        .click(function (e) {
            e.preventDefault();
        });
    

    Getting the element from the jQuery instance:

    var link = $("#preventlink")[0];
    link.addEventListener("click", function(e) {
      e.preventDefault()
    }, false);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a id="preventlink" href="http://youtube.com"> click here </a>

    Sticking with just jQuery:

    $("#preventlink").click(function(e) {
      e.preventDefault()
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <a id="preventlink" href="http://youtube.com"> click here </a>

    See jQuery's doc on the subject