Search code examples
jqueryfindappendjquery-selectors

Insert new DIV between two DIVs that have the same class and are immediate siblings


Struggling with this one for a while now. My markup simplified:

<div class=row>
    <div class="somediv"></div>
    <div class="somediv2"></div>
    <div class="elem"></div>
    <div class="elem"></div>
    <div class="somediv3"></div>
    <div class="somediv4"></div>
<div class=row>
....

I need to find a way to select all DIVs on document ready that: 1. has a class: elem 2. their next DIV also has the class name: elem. Then I need to insert a new DIV between them:

<div class=row>
    <div class="somediv2"></div>
    <div class="elem"></div>
    <div class="new"></div>
    <div class="elem"></div>
    <div class="somediv3"></div>
    <div class="somediv4"></div>
<div class=row> // and it goes...


$(document).ready( function () {
   if($('.elem').next().hasClass('.elem')) {
       $('<div class="new"></div>').appendTo().prev('.elem');
   } else {
   });
});

Solution

  • Try this:

    $(document).ready( function () {
       $('.elem + .elem').before($('<div class="new"></div>'));
    });
    

    It's using CSS's adjacent sibling selector (+). It finds an element with class .elem with another element with class .elem immediately preceding it, then adds a new div before it.

    Fiddle: http://jsfiddle.net/4r2k4/