2

I'm creating a JQuery object(let's call it $dummyHTML) and setting some html content inside it. Then I go through each of it's child nodes including text ones, do some checks, and append them to a new different JQuery Object(let's call it $refinedHTML).

But the problem is that the contents of $dummyHTML seems to be empty even before I append them to $refinedHTML!

Now, I know that JQuery append function doesn't copy a node, it actually transfers the node to the other JQuery object. So I'm guessing the append function triggers before I mean it to?

Here is a minified example of the issue.

var $dummyHTML = $('<div/>');
$dummyHTML.html('Hello there, <span>myself!</span>');

var $refinedHTML = $('<div/>');

console.log($dummyHTML[0]);
$dummyHTML.contents().each(function() {
 $refinedHTML.append($(this));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

But if I remove the .contents part the programs works as expected.

tomerpacific
  • 4,704
  • 13
  • 34
  • 52
  • "_append function triggers before I mean it to?_" Nope, the console log fires later than you think it would. – Teemu Dec 31 '18 at 09:19
  • 2
    The console is asynchronous. If you logged the actual value instead of the reference (`console.log($dummyHTML[0].innerHTML);` you'd see the correct value. When you're logging a reference, the content of the element changes before the object properties are actually listed to the the console, hence the missleading results. – Teemu Dec 31 '18 at 09:29
  • @Teemu this deserves to be wrote as answer, kindly do. – Alexandre Elshobokshy Dec 31 '18 at 09:31
  • @IslamElshobokshy This is more like a dup of https://stackoverflow.com/questions/23429203/weird-behavior-with-objects-console-log – Teemu Dec 31 '18 at 09:37
  • @Teemu but your answer is intuitive than the answers in the link you mentioned ^^ – Alexandre Elshobokshy Dec 31 '18 at 09:38
  • @IslamElshobokshy I don't know, I find zzzzBov's answer in that post even more intuitive as my comment ... – Teemu Dec 31 '18 at 09:41
  • @Teemu I won't keep on arguing, but it's all a matter of preference in understanding :) Happy New Year! – Alexandre Elshobokshy Dec 31 '18 at 09:42

1 Answers1

0

.contents() extracts the content of a DOM element .When you create an object on the fly,it is not yet a DOM element so .contents() will not work however you can manipulate the object data in other ways.

Reference here:

Given a jQuery object that represents a set of DOM elements, the .contents() method allows us to search through the immediate children of these elements in the DOM tree and construct a new jQuery object from the matching elements.

Ali Sheikhpour
  • 10,475
  • 5
  • 41
  • 82