用Div划分每两个Div

时间:2016-03-16 18:14:57

标签: javascript jquery

这是我的HTML

<div class="sections">

        <div class="section">
            <a href="javascript:void(0)" class="person-link" id="743512">
                <span class="name-role" id="743512">
                    Hellen Quesada <br> Principal Software Engineer
                </span>
            </a>
        </div>

        <div class="section">
            <a href="javascript:void(0)" class="person-link" id="743587">
                <span class="name-role" id="743587">
                    Jonathan Chavez <br> Principal Creative Engineer
                </span>
            </a>
        </div>

        <div class="section">
            <a href="javascript:void(0)" class="person-link" id="749058">
                <span class="name-role" id="749058">
                    Rodrigo Ovares <br> Creative Engineer
                </span>
            </a>
        </div>

        <div class="section">
            <a href="javascript:void(0)" class="person-link" id="750684">
                <span class="name-role" id="750684">
                    Juan Morera <br> Software Engineer
                </span>
            </a>
        </div>

        <div class="section">
            <a href="javascript:void(0)" class="person-link" id="763534">
                <span class="name-role" id="763534">
                    Magdiel Cordero <br> Sr. Frontend Engineer
                </span>
            </a>
        </div>

        <div class="section">
            <a href="javascript:void(0)" class="person-link" id="15">
                <span class="name-role" id="15">
                    Eric Marin <br> Sr. Creative Engineer
                </span>
            </a>
        </div>

        <div class="section">
            <a href="javascript:void(0)" class="person-link" id="16">
                <span class="name-role" id="16">
                    Mauricio Castro <br> Sr. Software Engineer
                </span>
            </a>
        </div>

        <div class="section">
            <a href="javascript:void(0)" class="person-link" id="17">
                <span class="name-role" id="17">
                    Luis Hernandez <br> Sr. Creative Engineer
                </span>
            </a>
        </div>

</div>

这是动态生成的HTML,所以我需要用jQuery做一些事情,以便用另一个section中的div类将每个2个元素包装成一个新类。

这样的东西
<div class sections>
 <div class wrapper>
  <div> class section>...content </div>
  <div> class section>...content </div>
 </div>
 <div class wrapper>
  <div> class section>...content </div>
  <div> class section>...content </div>
 </div class wrapper>
  <div> class section>...content </div>
  <div> class section>...content </div>
 </div>
</div>

所以你推荐什么?

1 个答案:

答案 0 :(得分:2)

您可以使用以下jQuery代码来包含具有div类的wrapper的每个其他部分。

var sections = $(".sections > .section");
for (var i = 0; i < sections.length; i += 2) {
    sections.slice(i, i + 2).wrapAll("<div class='wrapper'></div>");
}

https://jsfiddle.net/dehli/oun232yc/