Get html element after creation

I create img when I click on input, then I get html or anyelse from the created img.

but I do not know why this does not work!

always return null

my js:

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

i mande a exp .: Demo

+2
source share
3 answers

this indicates the wrong place in setInterval .

this , which you have in the outer scope, is not the same as this , which you get inside the callback, which will usually be a window object, because:

 setInterval(f, t) 

actually

 window.setInterval(f, t); 

To solve the problem, make a copy of this in the outer area:

 $("#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, like @TJ Crowder suggests that you could actually use the jQuery constructor to get this copy and save some jQuery calls:

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

Another problem is that .html() shows the internal content of the tags, not the tags themselves, and the img tag does not contain the internal content.

There seems to be no built-in jQuery method that returns the actual entire HTML element. To do this, you will need to put your element in something else (for example, a <div> ), and then take .html() this.

Here is the 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); 

Demonstration of its use in your problem at http://jsfiddle.net/alnitak/qaSmS/

+4
source

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

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

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

Other answers indicating that this used correctly in the timeout handler. However, when you fix this, the warning will just be empty.

0
source

Source: https://habr.com/ru/post/1387362/


All Articles