Search code examples
javascriptjqueryhtmlhrefselector

jQuery Selector for ahref within .html()


I am trying to use jQuery to select all the elements within the .html() functions and run a message on click. However this is not working, does anyone here know why?

    function load_tweets(user) {
      var $body = $('body');
      while(index >= 0){
        var $tweet = $('<div class="tweet"></div>');
        $tweet.html("<span class='tweetText'>"+tweet.created_at + ' <a href="#" class="'+tweet.user+'">@' + tweet.user + '</a>: ' + tweet.message+"</span>");
        $tweet.appendTo($body);

        index -= 1;
      }
    }
    $("a[href='#']").click(function() {
        alert($(this).attr("class"));
    });

Solution

  • You're trying to find the elements BEFORE you insert them. You have to put your $("a[href='#']") code AFTER you insert your elements.

    Or just use this instead. $("body").on("click", "a[href='#']", function() {