Take two randomly generated divs and wrap them in a custom div

I am trying to get the two randomly generated div identifiers shown below and wrap them in my custom div, which I can control. There was a search around the jQuery API for a solution, but there are still no ideas.

Here's a preliminary example: 2 Randomly Generated ID's + Custom Class

So, as you can see, there are two <div id="random_string"></div> and one custom <div class="wrap_awm"></div>

Since I cannot target the two IDs above, I donโ€™t know how to say jQuery, get two divs on top of wrap_awm and put them inside ".wrap_awm". Just how is it?

+4
source share
5 answers

What you are looking for is called .prevAll() :

 var $wrap = $('.wrap_awm'); $wrap.prevAll(':lt(2)').appendTo($wrap); 

In combination with the selector :lt() use only the first two elements.

+4
source

It's simple:

 var w = $(".wrap_awm"); w .prev() .prev() .addBack() .appendTo(w); 

See a live working example in JS Fiddle

+4
source
 $(".wrap_awm") .prev("div") .appendTo(".wrap_awm") .end() .prev("div") .appendTo(".wrap_awm"); 
+1
source

You can use the .prev () function in the jQuery API to select the previous brother of your custom div. Then you can save this and apply the same .prev () ie function to it:

 var previousSibling1 = $(".wrap_awm").prev(); var previousSibling2 = $(previousSibling1).prev(); 

You now have a link to your two previous siblings, and they can be moved to your custom div.

0
source

It is simple and straightforward, but probably not the way it should be done ...

 $(document).ready(function () { var prev1 = $('.wrap_awm').prev().prev(); var prev2 = $('.wrap_awm').prev(); $('.wrap_awm').html(prev1).append(prev2); }); 

Jsfiddle

0
source

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


All Articles