views:

46

answers:

2

if hovering over an element injects something into the DOM, can I still reference it?

Or do I have to use the live plugin?

i' using jqeury 1.3.2

i.e. can I do $("#someItem").attr("src", "htt..."); on it?

I am trying to do it, but I think its not working b/c its a newly added item to the DOM.

+1  A: 

Yes, an element that has been added to the DOM can be selected and referenced.

Or, if you already had a reference to it that you used when you added it to the DOM, you can continue to use that reference after it has been added as well.

Using this example, you can see that you can both use a current reference to a newly created element, as well as make a new reference to it.

http://jsfiddle.net/Czuvx/

HTML:

<div id='button'>hover me</div>

jQuery:

$('#button').hover(function() {
    $('#newElement').remove();

    var $myNewElement = $('<div id="newElement">new Element</div>');

    $('body').append($myNewElement);

    $myNewElement.css({color:'red'});
},
function() {

// This function has completely different namespace 
//   from the one that created and inserted #newElement
//   and I can get a reference to it just like any other element

    var $newReferenceToElement = $('#newElement');

    $newReferenceToElement.css({color:'blue'});
});
patrick dw
what if you don't have a reference to it previously? or it was lost.
Blankman
As you can see from the second function in the `hover()` event, it creates a new reference to the element that was added. `var $newReferenceToElement = $('#newElement');`
patrick dw
@Blankman - Does this make sense? Are you having some other trouble? Might need to share some code if so.
patrick dw
A: 

Showing a bit more of your code would be helpful, but I think I get the general idea.

If you're just looking to add events or something to that item, you can do it before you append the item.

(function($){
  $(function(){
    $("#link").hover(
      function(){
        var $div = $("<div class='inserted_div'></div>").bind("click",function(){ ... });
        $("body").append($div);
      }),
      function(){

      });
  });
})(jQuery);

So just bind the events or attributes at the time of creation, before you append it.

RussellUresti