使用jquery合并多个相同的html元素

时间:2013-02-11 14:10:12

标签: jquery

我喜欢只在div中移动文本,如下所示:

 <div class="field-item even">
 Job1<p><a href="">Name1</a></p>
 </div>

等...

我希望合并并删除所有.field-name-field-brief-text-team div

任何帮助请... 感谢

 <div class="field field-name-field-team field-type-entityreference">
   <label>Team</label>
   <div class="field-items">

     <div class="field-item even">
     <p><a href="">Name1</a></p>
     </div>

    <div class="field-item odd">
    <p><a href="">Name2</a></p>
    </div>

    <div class="field-item even">
      <p><a href="">Name3</a></p>
    </div>

   </div>
 </div>

<div class="field field-name-field-brief-text-team field-type-text">
    <div class="field-items">

    <div class="field-item even">Job1</div>
    <div class="field-item odd">Job2</div>
    <div class="field-item even">Job3</div>

</div>
</div>

2 个答案:

答案 0 :(得分:2)

我相信这可以满足您的要求:

$('.field-name-field-brief-text-team .field-item').each(function (i) {
    var to = $('.field-item').eq(i)[0],
        toFirst = to.getElementsByTagName('*')[0],
        from = this,
        txt = document.createTextNode(this.textContent);
    to.insertBefore(txt,toFirst);
}).remove();

JS Fiddle demo

以上略有改动的版本,使用另一种方法从jQuery选择器中检索DOM节点(使用get(0))并查找to节点的第一个子元素( to.firstChild)。这些仅仅是替代方案,并不一定建议采用以前的方法:

$('.field-name-field-brief-text-team .field-item').each(function (i) {
    var to = $('.field-item').eq(i).get(0),
        toFirst = to.firstChild,
        from = this,
        txt = document.createTextNode(this.textContent);
    to.insertBefore(txt,toFirst);
}).remove();

JS Fiddle demo

编辑提供最快(每JS Perf)方法:

$('.field-name-field-brief-text-team .field-item').each(function (i) {
    var to = $('.field-item')[i]
        toFirst = to.firstChild,
        txt = document.createTextNode(this.textContent);
    to.insertBefore(txt,toFirst);
}).remove();

JS Fiddle demo


已修改,以便在文本中添加请求的{在下面的评论中} :

$('.field-name-field-brief-text-team .field-item').each(function (i) {
    var to = $('.field-item')[i]
    toFirst = to.firstChild,
        txt = document.createTextNode(this.textContent + ': ');
    to.insertBefore(txt, toFirst);
}).remove();

JS Fiddle demo

参考文献:

答案 1 :(得分:1)

使用此:

$(document).ready(function() {
    target = $("div.field-name-field-team").find("div.field-item");
    source = $("div.field-name-field-brief-text-team").find("div.field-item");

    for(var i = 0; i < target.length; i++) {
        $(target[i]).html($(source[i]).html() + $(target[i]).html());
    }
});

输出:

<div class="field field-name-field-team field-type-entityreference">
   <label>Team</label>
   <div class="field-items">

     <div class="field-item even">Job1
     <p><a href="">Name1</a></p>
     </div>

    <div class="field-item odd">Job2
    <p><a href="">Name2</a></p>
    </div>

    <div class="field-item even">Job3
      <p><a href="">Name3</a></p>
    </div>

   </div>
 </div>

要删除所有.field-name-field-brief-text-team div,请使用

$("div.field-name-field-brief-text-team").remove()