Home .unwrap() doesn't work after .append().load()
Reply: 1

.unwrap() doesn't work after .append().load()

Alex S
Alex S Published in 2018-02-14 09:46:01Z

I am currently doing this:

$("div#js-product-list .products.row").append($("<div>").load('http://andreisdev.tk/alexstan/en/2-home?page=' + page_nr + ' .products.row article.product-miniature.js-product-miniature'));

Then I am incrementing the page_nr, that is not important in this question because it works.

After that I am trying to unwrap the articles just loaded in the page to make them siblings with the other articles already in the page, since load overrides the selection you make, I had to make that div at the end of all my current articles.

I am trying to unwrap them this way:

$('article.product-miniature.js-product-miniature ~ div article.product-miniature.js-product-miniature').unwrap();

So basically I am selecting the div just appended as sibling to the current articles I had then I'm selecting the articles just loaded inside that new div and trying to unwrap them.

If I am doing this in the console, first typing the command with .append().load() and run it, then the .unwrap() one it works totally fine, if I am inserting and runnning them both at the same time though it does not work, same thing that happens from my .js file.

I kind of succeded with:

setTimeout(function() {
  $('article.product-miniature.js-product-miniature ~ div article.product-miniature.js-product-miniature').unwrap(); 
}, 500);

But there has to be a direct way of doing it.

EDIT !!!

Since the comments won't be seen by too many, here's the response:

$("div#js-product-list .products.row").append($("<div>").load(''+link+' .products.row article.product-miniature.js-product-miniature', function() { $('article.product-miniature.js-product-miniature ~ div article.product-miniature.js-product-miniature').unwrap(); }));

Rory McCrossan
Rory McCrossan Reply to 2018-02-14 10:05:06Z

The issue is because load() is asynchronous, so you're attempting to unwrap elements that don't exist yet. This is why using the timeout to delay the logic works.

A better solution is to use the callback argument of load() to provide a function to execute your unwrap logic after the content has been added to the DOM. Like this:

$("div#js-product-list .products.row").append($("<div>").load('http://andreisdev.tk/alexstan/en/2-home?page=' + page_nr + ' .products.row article.product-miniature.js-product-miniature', function() {
  $('article.product-miniature.js-product-miniature ~ div article.product-miniature.js-product-miniature').unwrap();
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.303971 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO