在第一个子<div> </div> </div>之后用<div>标记包装内容

时间:2015-01-12 12:00:35

标签: javascript jquery html

我想在第一个孩子<div>

之后包装标签

这是html:

<details>
  <div class="first-child">Copyright 1999-2014.</div>
  <p> - by Refsnes Data. All Rights Reserved.</p>
  <p>All content and graphics on this web site are the property of the company Refsnes Data.</p>
</details>

我需要这样的输出:

<details>
     <div class="first-child">Copyright 1999-2014.</div>
     <div class="details_content">
       <p> - by Refsnes Data. All Rights Reserved.</p>
       <p>All content and graphics on this web site are the property of the company Refsnes Data.</p>
     </div>
</details>

这是我的尝试:但是,这不起作用。

$(document).ready(function(){
    var sum=$('.first-child').html();
    $('.first-child').remove();
    $('details').wrapInner('<div class="details_content"></div>');
    $('<div class="first-child">' + sum +'</div>').appendTo($('details'));
    $('.details_content').hide();
    $('.first-child').click(function(){
        $('.details_content').slideToggle(0);   
    });
});

Here is a fiddle

标记<div class="first-child">Copyright 1999-2014.</div>是在<details>标记的最后一个位置生成的。我希望将其生成为第一个孩子<div>

此外,是否有可用的优化解决方案?而不是编写这么多代码?

2 个答案:

答案 0 :(得分:2)

要将所有p元素包装在详细信息中,您可以这样做:

$('details p').wrapAll('<div class="details_content" />');

使用你的代码,你希望.first-child div成为第一个孩子而不是最后一个,你应该使用prepend而不是append:

$('<div class="first-child">' + sum +'</div>').prependTo($('details'));

答案 1 :(得分:1)

$(document).ready(function(){
    $("details").append('<div class="details_content"></div>');
    $("details p").appendTo(".details_content");


    $('.details_content').hide();
    $('.first-child').click(function(){
        $('.details_content').slideToggle(0);   
    });
});

......这应该以最短的方式完成工作

[forked Fiddle]

[编辑]:好的,Bhojendra Sah的代码少了一行;)

相关问题