Use Javascript Bookmarklet to Chunk Page Content by Headings

与世无争的帅哥 提交于 2019-12-02 04:24:10

You don't need jquery. Just walk the childNode pseudo-array (presumably of the body...a body element should be created even if not specified in the html), and build an output array of elements. When you hit a h1/h2/h3, you'll create a div, add it to the end of the array, as well as saving it as the "current element" which other elements will be added to. Once done, you can add those elements to the body (or put them somewhere else).

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]);
 }

You could insert jQuery from the bookmarklet, and then it's rather easy:

function a() {
    var names = {'h1': 'one',
                 'h2': 'two',
                 'h3': 'three',
                 'h4': 'four',
                 'h5': 'five',
                 'h6': 'six'};
    var i = 1;
    jQuery('*').filter(":header").each(function() {
        jQuery(this)
        .add(jQuery(this)
            .nextUntil( jQuery("*")
                        .filter(":header")) )
            .wrapAll( jQuery("<div class='" + names[this.nodeName.toLowerCase()] + "'>") );
    });
};

(function(){
    var s=document.createElement('script');
    s.src='http://code.jquery.com/jquery-1.6.1.js';
    document.getElementsByTagName('head')[0].appendChild(s);
    s.onload = function(){
        setTimeout(a, 500);
    };
})();

Or, in one line:

javascript:function a(){var b={h1:"one",h2:"two",h3:"three",h4:"four",h5:"five",h6:"six"};jQuery("*").filter(":header").each(function(){jQuery(this).add(jQuery(this).nextUntil(jQuery("*").filter(":header"))).wrapAll(jQuery("<div class='"+b[this.nodeName.toLowerCase()]+"'>"))})}(function(){var b=document.createElement("script");b.src="http://code.jquery.com/jquery-1.6.1.js";document.getElementsByTagName("head")[0].appendChild(b);b.onload=function(){setTimeout(a,500)}})();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!