Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get single page inner text?

Using CSS3 columns to take a somewhat large text document and make it scroll horizontally. Here is demo of code.- http://jsfiddle.net/wojtiku/bFKpa/

I use "document.documentElement.innerText" js code ,get all document text,but I want to get a column text,How to do ?

like image 595
HelloWorld Avatar asked Dec 06 '25 09:12

HelloWorld


1 Answers

You can get the root element of each column and the innerText from that element.

var elements = document.getElementById("container").getElementsByTagName("p");
for(var i = 0; i < elements.length; ++i) {
    console.log("COLUMN " + i + "\n");
    console.log(elements[i].innerText);
};

fiddle: http://jsfiddle.net/4mHCb/3/

You can open your browser's JS console and see the output (ctrl+shift+j in chrome).

EDIT

Thanks to voithos for pointing out what I overlooked. Taking what he said into account, I'm pretty sure there is no way to do this accurately. However, here is a total hack which approximates what you are looking for. It uses an offscreen canvas and the 2d context's mesaureText method: http://jsfiddle.net/4mHCb/5/

var elements = document.getElementById("container").getElementsByTagName("p");
var g2d = document.createElement("canvas").getContext("2d");
var containerStyle = document.getElementById("container").style;

var columnWidth = 150;
var lineHeight = 18;
var columnHeight = 300;
var linesPerCol = columnHeight / lineHeight;
var results = [];
for(var i = 0; i < elements.length; ++i) {
    var colText = elements[i].innerText;
    var textWidth = g2d.measureText(colText).width;
    var numCols = textWidth / (columnWidth * linesPerCol);

    var charIdx = 0;
    for (var column = 0; column < numCols; ++column) {
       var currString = "";
       var currTextWidth = 0;
       for (; charIdx < colText.length && currTextWidth < columnWidth*linesPerCol;    ++charIdx) {
           currString += colText[charIdx];
           currTextWidth = g2d.measureText(currString).width;
       }
       results.push(currString);
   }
}

for(var column = 0; column < results.length; ++column) {
   console.log("COLUMN: " + column);
   console.log(results[column]);
}

like image 97
Matt Wonlaw Avatar answered Dec 08 '25 21:12

Matt Wonlaw