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

Fight this for a while. My markup is 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 the DIVs on the finished document, which: 1. has a class: elem 2. their next DIV also has a 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 { }); }); 
+6
source share
3 answers

Try the following:

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

It uses a CSS contiguous selector ( + ). It finds an element with class .elem with another element with class .elem immediately preceding it, then adds a new div in front of it.

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

+13
source

Non-jQuery solution:

 var divs, str; divs = document.getElementsByClassName( 'elem' ); [].slice.call( divs ).forEach(function ( div ) { str = ' ' + div.nextElementSibling.className + ' '; if ( str.indexOf( ' elem ' ) !== -1 ) { div.insertAdjacentHTML( 'afterend', ' <div class="new">X</div> ' ); } }); 

Live demo: http://jsfiddle.net/2MfgB/2/

"But Šime, this does not work in IE8 ..." :P


Update:
Alternative solution:

 var divs = document.querySelectorAll( '.elem + .elem' ); [].slice.call( divs ).forEach(function ( div ) { div.insertAdjacentHTML( 'beforebegin', ' <div class="new">X</div> ' ); }); 

Live demo: http://jsfiddle.net/2MfgB/3/

+3
source

Your code looks very good to me. You just do not need to wrap it in each , so that it works on each of them?

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

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


All Articles