Skip to content Skip to sidebar Skip to footer

Get The Html Element After Created

i'm creating a img when i click in a input, then i get the html or anyelse from the created img. but i dont know why this is not working! always return null my js: $('#click').clic

Solution 1:

this is pointing at the wrong place in setInterval.

The this you have in the outer scope isn't the same as the this that you get inside the callback, which will usually be the window object, since:

setInterval(f, t)

is actually

window.setInterval(f, t);

To solve the problem, take a copy of this in the outer scope:

$("#click").click(function(){
    var self = this;
    var $imgDone = $('<img/>').attr('src', 'someImage/insomewhere.jpg');
    $(this).after($imgDone);
    setTimeout(function(){
          alert($(self).next().html());
    }, 1000);
});

For efficiency, as @T.J. Crowder suggests, you could actually use the jQuery constructor to take that copy, and save yourself a few calls to jQuery:

$("#click").click(function(){
    var $this = $(this);
    var $imgDone = $('<img/>')
         .attr({src:  'someImage/insomewhere.jpg'})
         .insertAfter(this); // NB: not $this heresetTimeout(function(){
          alert($this.next().html());
    }, 1000);
});

The other problem is that .html() shows the inner contents of tags, not the tags themselves, and your img tag has no inner contents.

There doesn't appear to be any builtin jQuery method that returns the actual whole HTML of an element. To do that you'd need to put your element into something else (e.g. a <div>) and then take the .html() of that.

Here's a plugin I just made that does this, inspired by something I found via Google:

(function($) {
    $.fn.outerhtml = function() {
        return $('<div/>').append(this.clone()).html();
    };
})(jQuery);

Demo of it in use on your problem at http://jsfiddle.net/alnitak/qaSmS/

Solution 2:

because the timeout function is called form a different context, this no longer applies.

$("#click").click(function(){
    var $imgDone = $('<img/>').attr('src', 'someImage/insomewhere.jpg');
    $(this).after($imgDone);
    myImg = $(this);
    setTimeout(function(){
          alert($(myImg).next().html());
    }, 1000);
});

Solution 3:

The ".html()" method gets the contents of something, not including the markup for the container itself.

The other answers indicating that the use of this in the timeout handler are correct, of course. When you fix that, however, the alert will just be empty.

Post a Comment for "Get The Html Element After Created"