Created
December 3, 2011 17:30
-
-
Save uu59/1427649 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function detectMainContent(){ | |
// based on JimmyWales http://d.hatena.ne.jp/ofk/20101123/1290439104 | |
var scoreCalc = function(elm){ | |
var nodeTable = { | |
"div": 0, | |
"article": 50, | |
"section": 5 | |
}; | |
var clsTable = { | |
"content": 5, | |
"entry": 5, | |
"columns": 5, // techcrunch | |
"post": 5, | |
"main": 1, | |
"body": 1, | |
"article": 10, | |
"sidebar": -10, | |
"header": -10, | |
"footer": -10, | |
"wrapper": -10, | |
"container": -10 | |
} | |
var score = nodeTable[elm.nodeName.toLowerCase()]; | |
if(elm.className.length > 0){ | |
score += 1; | |
} | |
if(elm.getAttribute('id')){ | |
score += 1; | |
} | |
for(var cls in clsTable){ | |
var id = (elm.getAttribute('id') || "").toLowerCase(); | |
var klass = elm.className.toLowerCase(); | |
if(klass.indexOf(cls) > -1){ | |
score += clsTable[cls]; | |
} | |
if(id.indexOf(cls) > -1){ | |
score += clsTable[cls]; | |
} | |
if(id == cls){ | |
score += clsTable[cls] * 3; | |
} | |
if(klass == cls){ | |
score += clsTable[cls] * 2; | |
} | |
} | |
return score; | |
} | |
var elements = Array.prototype.slice.call(document.querySelectorAll('div, article, section')); | |
var mostImportant = { | |
elm: document.querySelector('body'), | |
square: 0, | |
score: 0 | |
}; | |
elements.forEach(function(elm){ | |
var score = scoreCalc(elm); | |
var b = elm.getBoundingClientRect(); | |
var square = b.height * b.width; | |
if(mostImportant.score < score){ | |
mostImportant = { | |
elm: elm, | |
score: score, | |
square: square | |
} | |
}else if(mostImportant.score == score){ | |
if(mostImportant.square < square){ | |
mostImportant = { | |
elm: elm, | |
score: score, | |
square: square | |
} | |
} | |
} | |
}); | |
// mostImportant.elm.setAttribute('style', 'border: 5px solid red;'); | |
return mostImportant.elm; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment