How to...">

In jQuery, how can I add something as a brother?

For example, suppose I have

<div class="sibling1"></div> <div class="sibling3"></div> 

How to insert

 <div class="sibling2"></div> 

Between the above? I tried preend, but it makes the child not native

+6
source share
3 answers

There are many different options in jQuery for inserting content at a specific position. All of this is well described on the jQuery documentation page for inserting the DOM outside the object .

To insert content outside an existing element (for example, not a child), but located relative to this object, you have four parameters shown in this jQuery doc screenshot:

enter image description here

The difference between the first two and the last two is solely what arguments are. For the first two, the location to insert is in the jQuery object, and the content is in the function argument. For the last two, the content to be inserted is in the jQuery object, and the destination is in the function argument. Due to the chain of several function calls, sometimes one or the other is more convenient.

As you can see, this allows you to insert content before or after an existing object (which will make it related to this object).

If you want it to be a child of this object, you can use any six jQuery methods that can set / change internal content, including .append() , .appendTo() , .html() , etc.

+15
source

Use after , for example:

 $('.sibling1').after('<div class="sibling2"></div>'); 

You can also use identifiers instead of classes, which seems more correct to me:

 <div id="sibling1" class="sibling"></div> <div id="sibling3" class="sibling"></div> 

And then use:

 $('#sibling1').after('<div id="sibling2" class="sibling"></div>'); 
+3
source

http://api.jquery.com/insertBefore/ :

 $('<div class="sibling2"></div>').insertBefore($('.sibling3')); 
-1
source

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


All Articles