开发者

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

开发者 https://www.devze.com 2023-04-05 08:09 出处:网络
Struggling with this one for a while now. My markup simplified: <div class=row> <div class=\"somediv\"></div>

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="s开发者_JAVA百科omediv3"></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 {
   });
});


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/


The 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 doesn't 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/


Your code looks pretty good to me. Don't you just need to wrap it in a each so that it fires on each one?

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

精彩评论

暂无评论...
验证码 换一张
取 消