使用Javascript书签按标题分块页面内容
作者:互联网
我有一个HTML页面,该页面是从数据库进行动态编译的,需要重新设置样式并进行重组.我知道它看起来很乱,但是我正在用的是这个(注意:没有< head>或< body>标签):
<p>Some paragraph</p>
<h1>Heading 1</h1>
<p>Some paragraph</p>
<p>Some paragraph</p>
<h2>Heading 2</h2>
<p>Some paragraph</p>
<p>Some paragraph</p>
<h3>Heading 3</h3>
<p>Some paragraph</p>
<p>Some paragraph</p>
...
我正在尝试编写一个JavaScript小书签,该小书签将重新格式化该页面并将其重新划分为分类的< div> ;,以便我可以对其进行重新样式设置.换句话说,我需要它像这样结束:
<p>Some paragraph</p>
<div class="one">
<h1>Heading 1</h1>
<p>Some paragraph</p>
<p>Some paragraph</p>
</div>
<div class="two">
<h2>Heading 2</h2>
<p>Some paragraph</p>
<p>Some paragraph</p>
</div>
<div class="three">
<h3>Heading 3</h3>
<p>Some paragraph</p>
<p>Some paragraph</p>
</div>
<div class="two">
<h2>Heading 2</h2>
<p>Some paragraph</p>
<p>Some paragraph</p>
</div>
请注意,我无法对现有页面执行任何操作;我必须通过小书签或附加组件来执行此操作.
解决方法:
您不需要jquery.只需遍历childNode伪数组(大概是body …即使未在html中指定,也应创建body元素),然后构建元素的输出数组.当您点击h1 / h2 / h3时,您将创建一个div,将其添加到数组的末尾,并将其另存为将添加其他元素的“当前元素”.完成后,您可以将这些元素添加到主体(或将它们放置在其他位置).
var parent = document.body, i;
// copy into temp array, since otherwise you'll be walking
// an array (childnodes) whose size is changing as elements
// get removed from it
var tmpArray = [];
for (i=0; i<parent.childNodes.length; i++)
tmpArray.push(parent.childNodes[i]);
var tagToClassMap = {H1: "one", H2: "two", H3: "three"};
var newArray = [], currElem = null;
for (i=0; i<tmpArray.length; i++) {
var elem = tmpArray[i];
var className = null;
if (elem.tagName && (className = tagToClassMap[elem.tagName]) != null) {
currElem = document.createElement("div");
currElem.className = className;
newArray.push(currElem);
currElem.appendChild (elem);
}
else {
if (currElem)
currElem.appendChild (elem);
else
newArray.push(elem);
}
}
parent.innerHTML = '';
for (i=0; i<newArray.length; i++) {
parent.appendChild (newArray[i]);
}
标签:bookmarklet,javascript 来源: https://codeday.me/bug/20191013/1904657.html