Use Javascript Bookmarklet to Chunk Page Content by Headings (part 2)
I've some javascript that @pimvdb helped me with here, and I was wondering if it could be tweaked so that it wo开发者_JAVA技巧uld group lesser heading's div
's within the next higher's div
.
In other words, start with this HTML:
<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>
<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>
...
… and then use javascript (via a bookmarklet because it all has to be done client-side) to end up with this:
<div class="one">
<h1>Heading 1</h1>
<p>paragraph</p>
<div class="two">
<h2>Heading 2</h2>
<p>paragraph</p>
<div class="three">
<h3>Heading 3</h3>
<p>paragraph</p>
</div>
<div class="three">
<h3>Heading 3</h3>
<p>paragraph</p>
</div>
</div>
</div>
<div class="one">
<h1>Heading 1</h1>
<p>paragraph</p>
<div class="two">
<h2>Heading 2</h2>
<p>paragraph</p>
<div class="three">
<h3>Heading 3</h3>
<p>paragraph</p>
</div>
</div>
</div>
How about just assigning classes to each different header instead of using :header, use each element type individualy and work from the highest to the lowest.
function a() {
$('h3').each(function() {
$(this)
.add($(this).nextUntil( $("h3")) ).wrapAll( $("<div class='three'>") );
});
$('h2').each(function() {
$(this)
.add($(this).nextUntil( $("h2")) ).wrapAll( $("<div class='two'>") );
});
$('h1').each(function() {
$(this)
.add($(this).nextUntil( $("h1")) ).wrapAll( $("<div class='one'>") );
});
};
Altered my answer to part one:
var parent = document.body, i;
var tmpArray = [];
for (i=0; i<parent.childNodes.length; i++)
tmpArray.push(parent.childNodes[i]);
var headerArray = [];
var classNames = [null, "one", "two", "three", "four", "five"]
var newArray = [], currElem = null;
for (i=0; i<tmpArray.length; i++) {
var elem = tmpArray[i];
var tagData = null;
var which;
if (elem.tagName &&
elem.tagName.charAt(0) == 'H' &&
(which = parseInt(elem.tagName.charAt(1))) > 0) {
currElem = document.createElement("div");
currElem.className = classNames[which];
currElem.appendChild (elem);
headerArray[which] = currElem;
if (which > 1)
headerArray[which-1].appendChild(currElem);
else
newArray.push(currElem);
}
else {
if (currElem)
currElem.appendChild (elem);
else
newArray.push(elem);
}
}
parent.innerHTML = '';
for (i=0; i<newArray.length; i++) {
parent.appendChild (newArray[i]);
}
精彩评论