带有字符串
<h1>aa</h1><p>xx</p><p>yy</p><h1>aaa</h1><p>xxx</p><p>yyy</p>
我试图在 header
之后插入一个 div 容器,将 header
的文本作为其 id
和内容 (下一个 header 之前的所有内容)在 header 之后,这样它就变成
<h1>aa</h1><div id="aa"><p>xx</p><p>yy</p></div><h1>aaa</h1><div id="aaa"><p>xxx</p><p>yyy</p></div>
到目前为止,这就是我所做的
let s = "<h1>aa</h1><p>xx</p><p>yy</p><h1>aaa</h1><p>xxx</p><p>yyy</p>";
const parser = new DOMParser();
const doc = parser.parseFromString(s, 'text/html');
const elems = doc.body.querySelectorAll('*');
[...elems].forEach(el => {
if (el.textContent !== '' && el.tagName === 'H1') {
el.insertAdjacentHTML('afterend', `<div id='${el.textContent}' />`)
//
}
});
console.log(doc.body.innerHTML);
是否有更简单的方法可以做到这一点,例如在标题后面添加一个开始 div 并在下一个标题之前添加一个结束 div ?我找不到太多这样的例子,Google 有更多 xml、php 或 java 使用 DOMParser
最佳答案
创建 DIV
即时使用 Document.createElement()
并移动<P>
元素使用 .appendChild()
let s = "<h1>aa</h1><p>xx</p><p>yy</p><h1>aaa</h1><p>xxx</p><p>yyy</p>";
const parser = new DOMParser();
const doc = parser.parseFromString(s, 'text/html');
const elems = doc.body.querySelectorAll('*');
[...elems].forEach(el => {
if (el.textContent !== '' && el.matches('H1')) {
// create div container
var div = document.createElement('div');
//Set Id
div.id = el.textContent;
// Get the next sibling next until H1
var siblings = nextUntil(el, 'H1');
for (var i = 0; i < siblings.length; i++) {
// move sibling into div
div.appendChild(siblings[i]);
}
// insert div before el in the DOM tree
el.parentNode.insertBefore(div, el.nextSibling);
}
});
function nextUntil(elem, selector) {
// Setup siblings array
var siblings = [];
// Get the next sibling element
elem = elem.nextElementSibling;
// As long as a sibling exists
while (elem) {
// If we've reached our match
if (elem.matches(selector))
break;
// Otherwise, push it to the siblings array
siblings.push(elem);
// Get the next sibling element
elem = elem.nextElementSibling;
}
return siblings;
}
console.log(doc.body.innerHTML);
关于javascript - 使用 DOMParser 在每个 header 后添加 div 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50968100/