Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 {
   });
});
like image 277
elbatron Avatar asked Sep 14 '11 14:09

elbatron


1 Answers

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/

like image 73
Matt Bradley Avatar answered Oct 14 '22 04:10

Matt Bradley