从document.createElement移除包装器div

时间:2019-03-01 23:24:15

标签: javascript jquery

我一直坚持这个时间最长,这让我发疯。我尝试了十二种不同的方法,但无法弄清楚如何使其工作。任何帮助,将不胜感激!!谢谢

这是我的代码:

<script>
  function runScript() {
    //get parent of script element
    var element = document.currentScript.parentElement;
    //my html string that needs to be inserted inside the original div
    var item = "<div>test1</div><div>test2</div>";

    //My current method. this method works but creates another wrapper div. I need a way to remove the wrapper div or a different method altogether without any wrapper divs.
    var z = document.createElement('div');
    z.innerHTML = item;
    element.appendChild(z);
  }
</script>


<div id="main-wrapper">
  <script>
    runScript();
  </script>
</div>

3 个答案:

答案 0 :(得分:1)

<script>
  function runScript() {
    //get parent of script element
    var element = document.currentScript.parentElement;
    //my html string that needs to be inserted inside the original div
    var item = "<div>test1</div><div>test2</div>";
    element.innerHTML = item;
  }
</script>


<div id="main-wrapper">
  <script>
    runScript();
  </script>
</div>

答案 1 :(得分:1)

使用jQuery标记后,您可以按以下方式创建元素:

$(item);

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
  function runScript() {
    var item = "<div>test1</div><div>test2</div>";
    $(document.currentScript.parentElement).append($(item));
  }
</script>


<div id="main-wrapper">
  <script>
    runScript();
  </script>
</div>

答案 2 :(得分:1)

您可以使用insertAdjacentHTML方法。

<script>
  function runScript() {
    //get parent of script element
    var element = document.currentScript.parentElement;
    //my html string that needs to be inserted inside the original div
    var item = "<div>test1</div><div>test2</div>";
    element.insertAdjacentHTML('beforeend', item);
  }
</script>


<div id="main-wrapper">
  <script>
    runScript();
  </script>
</div>

或者使用模板代替DIV。

<script>
  function runScript() {
    //get parent of script element
    var element = document.currentScript.parentElement;
    //my html string that needs to be inserted inside the original div
    var item = "<div>test1</div><div>test2</div>";

    var z = document.createElement('template');
    z.innerHTML = item;
    element.appendChild(z.content);
  }
</script>


<div id="main-wrapper">
  <script>
    runScript();
  </script>
</div>