我想在特定元素后插入html,但insertAdjacentHTML不会让我先添加一个结束标记。

如果我做

elm.insertAdjacentHTML('afterend', '</div><section class="block">');


预期的结果是

 <element></element></div><section class="block">


返回的结果

 <element></element><section class="block"></div>


有没有解决的办法?

编辑:

基本上我想做的是循环遍历每个元素并将它们分成两个div

 <div class="column">
     <div class="block">block 1</div>
     <div class="block">block 2</div>
     <div class="block">block 3</div>
     <div class="block">block 4</div>
     <div class="block">block 5</div>
     <div class="block">block 6</div>
     <div class="block">block 7</div>
     <div class="block">block 8</div>
 </div>


预期结果

 <div class="column">
     <div class="block">block 1</div>
     <div class="block">block 2</div>
     <div class="block">block 3</div>
     <div class="block">block 4</div>
</div>
<div class="column">
     <div class="block">block 5</div>
     <div class="block">block 6</div>
     <div class="block">block 7</div>
     <div class="block">block 8</div>
 </div>


JS

const blocks = document.querySelectorAll(".block");
    let half = Math.ceil(blocks.length / 2 - 1);
    blocks[half].insertAdjacentHTML('afterend', '</div><div class="column">');

最佳答案

如果我的要求正确,这就是您要执行的操作:

elm.parentNode.insertAdjacentHTML('afterend', '<section class="block"></section>');


如果div不是直接父元素,则可能要使用Element.closest(selector)代替:

elm.closest('div.myDiv').insertAdjacentHTML('afterend', '<section class="block"></section>');


更新

您已进一步详细说明了您的要求,这是使用Javascript进行的操作:



const blocks = [...document.querySelectorAll('.block')];

const middle = Math.ceil(blocks.length / 2 - 1);

const column = document.querySelector('.column');

const parent = document.querySelector('.parent');

const col1 = document.createElement('div');
col1.className = 'column';
const col2 = document.createElement('div');
col2.className = 'column';

blocks.forEach((block, index) => {
  if (index <= middle) {
    col1.appendChild(block)
  } else {
    col2.appendChild(block)
  }
})

parent.removeChild(column)
parent.appendChild(col1);
parent.appendChild(col2);

.column+.column {
  color: green;
}

<div class="parent">
  <div class="column">
    <div class="block">block 1</div>
    <div class="block">block 2</div>
    <div class="block">block 3</div>
    <div class="block">block 4</div>
    <div class="block">block 5</div>
    <div class="block">block 6</div>
    <div class="block">block 7</div>
    <div class="block">block 8</div>
  </div>
</div>





产生的DOM:

关于javascript - insertAdjacentHTML无法正确插入传递的字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52150384/

10-11 12:37