简体   繁体   中英

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

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 article s just loaded in the page to make them siblings with the other article s 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 article s I had then I'm selecting the article s 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(); }));

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();
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM