我想在特定元素后插入html,但是insertAdjacentHTML不会让我先添加一个结束标记。
如果我这样做
<Animatable.View animation={this.props.animation} style = {styles.innerView2}>
<Text text = "abcd" style = {{alignItems: 'flex-start', width: DEVICE_WIDTH - 20, textAlign: 'left'}}/>
</Animatable.View>
预期结果是
elm.insertAdjacentHTML('afterend', '</div><section class="block">');
返回结果
<element></element></div><section class="block">
有没有办法解决这个问题?
修改:
基本上我想做的是遍历每个元素并将它们分成两个divs
<element></element><section class="block"></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>
JS
<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>
答案 0 :(得分:1)
如果我对您的要求正确无误,这就是您想要做的:
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: