Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In jQuery how can I add something as a sibling?

Tags:

jquery

For example suppose I have

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

How can I insert

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

Between the above? I have tried prepend but this makes a child not a sibling

like image 946
Hoa Avatar asked Apr 29 '12 15:04

Hoa


People also ask

What is siblings method in jQuery?

The siblings() is an inbuilt method in jQuery which is used to find all siblings elements of the selected element. The siblings are those having same parent element in DOM Tree. The DOM (Document Object Model) is a World Wide Web Consortium standard. This is defines for accessing elements in the DOM tree.

How do you append something in jQuery?

jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.

Which function in jQuery is used to grab a previous sibling element?

The prev() method returns the previous sibling element of the selected element. Sibling elements are elements that share the same parent.

What is sibling in JavaScript?

Siblings are nodes with the same parent (in the same childNodes list). Element Siblings are elements with the same parent (in the same children list).


1 Answers

In jQuery, there are a number of different options for inserting content in a particular position. It is all described quite well in the jQuery documentation page for DOM insertion outside an object.

To insert content outside an existing element (e.g. not a child), but positioned relative to that object, you have four options shown in this jQuery doc screenshot:

enter image description here

The difference between the first two and the last two is solely in which arguments are which. For the first two, the location for inserting 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. Because of chaining of multiple function calls, sometimes one or the other is more convenient.

As you can see, this lets you insert content before or after an existing object (which will make it a sibling of that object).

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

like image 165
jfriend00 Avatar answered Oct 18 '22 18:10

jfriend00