In jQuery, how can I add something as a brother?
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:
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.
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>');
http://api.jquery.com/insertBefore/ :
$('<div class="sibling2"></div>').insertBefore($('.sibling3'));