使用javascript在DOM中注入DIV容器

时间:2015-02-04 07:55:54

标签: javascript html

我想知道如何使用javascript在DOM中的元素周围创建容器?我之前已经成功地在html中注入了DIVs straght,但是需要针对一些元素并将它们放在容器内并且不确定如何。

这是html:

<div class="menubar">
  <div class="searching myClass yourClass"></div>
  <ul class="navVoordelen">
    <li></li>
    <li></li>
  </ul>
  <a class="navLogo"></a>
  <div class="langsel"></div>
  <a class="navLogin"></a>
  <a class="navLogin"></a>
  <a class="navLogin"></a>
  <ul class="newnav clearfix animated">
    <li></li>
    <li></li>
  </ul>
</div>

我需要将容器放在父菜单DIV下面,并在第二个UL类之前结束。这就是我想要的样子:

<div class="menubar">
  <div div="container">
    <div class="searching myClass yourClass"></div>
    <ul class="navVoordelen">
      <li></li>
      <li></li>
    </ul>
    <a class="navLogo"></a>
    <div class="langsel"></div>
    <a class="navLogin"></a>
    <a class="navLogin"></a>
    <a class="navLogin"></a>
  </div>
  <ul class="newnav clearfix animated">
    <li></li>
    <li></li>
  </ul>
</div>

2 个答案:

答案 0 :(得分:1)

您可以在javascript中使用以下代码

var div = '<div class="container">';
var closediv = '</div>';
theParent =document.getElementsByClassName("menubar");
theParent.insertBefore(div, theParent.firstChild);

document.getElementsByClassName("menubar").appendChild(closediv);

答案 1 :(得分:0)

我建议采用以下方法:

function wrapAllPrevious() {
  // this is assigned via the Function.prototype.call()
  // method, later:
  var _self = this,
      // creating a <div> element:
      div = document.createElement('div');
  // assigning an 'id' to that created-<div>:
  div.id = 'demo';

  // inserting the created-<div> before the _self/this
  // element, using insertBefore():
  _self.parentNode.insertBefore(div, _self);
  // while the created-<div> has a previousSibling:
  while (div.previousSibling) {
    // we insert that previous-sibling before firstChild
    // of the <div> (effectively prepending the element
    // to the created-<div>):
    div.insertBefore(div.previousSibling, div.firstChild);
  }
}

// calling the function, using (as noted earlier)
// Function.prototype.call() to assign the specified
// <ul> as the 'this' of the function (using
// document.querySelector() to return the specific node:
wrapAllPrevious.call(document.querySelector('ul.newnav.clearfix.animated'));
#demo {
  border: 2px solid #f00;
}

#demo::before {
  content: "Newly-added <div> element.";
}
<div class="menubar">
  <div class="searching myClass yourClass"></div>
  <ul class="navVoordelen">
    <li></li>
    <li></li>
  </ul>
  <a class="navLogo"></a>
  <div class="langsel"></div>
  <a class="navLogin"></a>
  <a class="navLogin"></a>
  <a class="navLogin"></a>
  <ul class="newnav clearfix animated">
    <li></li>
    <li></li>
  </ul>
</div>

参考文献: