joehungjohn joehungjohn - 6 months ago 15
jQuery Question

What is the difference between a dom element originally in the code, versus one that is added later?

For some reason, when I take a block of html, remove it, and then add it to the same place that it came from, I can't perform operations on the elements. Any idea why?

Something like this:

<div id="container">

<img src="img.png" id="img1" height="auto">
<img src="img2.png" id="img2" height="auto">

</div>

<script>

var imgWidth = 0;

function getImageWidth() {

imgWidth = $("#img1").width();

}

getImageWidth(); // this will run

// but if I remove say both images, then add them back
$("#img1, #img2").remove();

var block = '<img src="img.png" id="img1" height="auto">' + '\n' +
'<img src="img2.png" id="img2" height="auto">' + '\n';

$("#container").append(block);

getImageWidth(); // this will not run, but no errors are thrown either

</script>

Answer

Just added some real image links to your Fiddle, swapping them when the removed DOM gets re-added so you can tell the new width gets read and logged, seems to be working fine in Chrome: https://jsfiddle.net/ibarsi/umxxbcpm/

What browser are you using to test this?

Here's my script changes in-case the link dies.

var imgWidth = 0;

function getImageWidth() {
  imgWidth = $("#img1").width();
  return imgWidth
}

console.log("FIRST", getImageWidth());

$("#img1, #img2").remove();

var block = '<img src="http://blogmedia.jaludo.com/titter/wp-content/uploads/2012/05/cute-animals4.jpg" id="img1" height="auto">' + '\n' +
    '<img src="https://s-media-cache-ak0.pinimg.com/736x/3a/a8/bd/3aa8bd1b9a1befe4fc77c1556e16a5f8.jpg" id="img2" height="auto">' + '\n';

$("#container").append(block);

console.log("SECOND", getImageWidth());