views:

38

answers:

2

I just appended some html to another JQuery object. I want to get a reference to the newly created dom node so that I can call another function on it. As seen in the code below, I am not getting a reference to what I wanted. Instead of the new node, I am getting the node with the original id.

var a = $("#id").append("some_html");
a.live('click', function(event){
    alert("hello!");
});
+3  A: 

It depends on what the HTML is. If it can be contained in a div then do this:

var a = $("some_html").appendTo("#id");

A full example (using 1.4+ syntax) is this:

var a = $("<a />", { href: "/new/page", text: "Click Me" }).appendTo("#id");

This difference is append returns the parent object (it doesn't break the existing chain), and appendTo returns the newly created object, even after it is appended.

EDIT: Also, you are using live incorrectly. In this situation, just use bind or the click helper method:

a.click(function(event){
    alert("hello!");
});

Best use: Finally, using jQuery 1.4+, you can just do this, no variable retention necessary:

$("<a />", { 
  href: "#", 
  text: "Click Me",
  click: function (e) {
    e.preventDefault();
    alert("hello!");
  } 
}).appendTo("#id");
Doug Neiner
Doug - Same comment I left for Matt, `$("some_html")` doesn't create an element, but rather searches the DOM for `<some_html>text</some_html>`.
patrick dw
@patrick - When replaced with the *actual* html (e.g. `"<div>Stuff</div>"`) it'll create it :)
Nick Craver
@Doug - Actually his `live` will work, on that chain the selector is still `#id`, you can see a quick test here using [`.selector`](http://api.jquery.com/selector/): http://jsfiddle.net/PzPgY/
Nick Craver
@Nick - There I go, getting all literal again. :o) Sorry, Doug. +1
patrick dw
@Nick, though his code *would* work, it wasn't doing what he wanted... and a `live` event on a newly added DOM node (as he explained he wanted) does not make sense.
Doug Neiner
A: 
var newNode = $('some_html');
$('#id').append(newNode);

newNode.live('click', function(event) {
    alert('hello!');
});
Matt Huggins