javascript - 在第一个子 <div> 之后使用 <div> 标签包装内容

标签 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> .

还有,有没有可用的优化方案?而不是编写这么多代码?

最佳答案

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

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

在您的代码中,您希望 .first-child div 成为第一个子级而不是最后一个,您应该使用前置而不是附加:

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

关于javascript - 在第一个子 <div> 之后使用 <div> 标签包装内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27901495/

相关文章:

javascript - 自动完成功能不随表单提交发送数据

javascript - 如何创建一个 slider 来更改主页内容以及 slider 内容并为过渡设置动画?

javascript - 使用 d3.tip 添加鼠标悬停效果

javascript - React Native 链接短信

javascript - firefox »find as you type« 与 JavaScript 键事件冲突

jquery - 从同源 URL 获取页面元素的 CSS 属性值

javascript - 将 native 浏览器事件对象转换为 jQuery 事件对象

javascript - 如何将环境特定的 URL 获取到我的 AngularJS Controller 中?

javascript - 我可以在单个组件中进行多次提取吗?

jQuery 验证和 css 位置