Melye77 Melye77 - 5 months ago 12
HTML Question

Get all text as a string from page

I want to get all the text from an html page into a string a print it on the console. So far I have this piece of code that works only partially because document.body.innerText returns the text together with line brakes which I certainly dont want. I want all my text to appear in 1 line

<html>
<head>
<h1>wtf</h1>
</head>
<body>
<div>dddiiiv</div>
<a>aaaaa</a>
<p>ppp</p>
<div>div</div>
<div id="impar"></div>
<div id="par"></div>
<div id="all"></div>
<script>
var elems = document.body.innerText;
var odd = "";
var even = "";
var all = "";
for (k in elems){
all = all + elems[k];
if (k % 2 === 0) {
even = even + elems[k]
} else {
odd = odd + elems[k]
}
}


console.log(all);
console.log(odd);
console.log(even);
</script>
</body>
</html>


Any idea of a get around for the innerText's brakes?

Answer

i have used .trim() and codepen URL for reference -http://codepen.io/nagasai/pen/jrPpeK

    <html>
        <head>
            <h1>wtf</h1>
        </head>
        <body>
            <div>dddiiiv</div>
            <a>aaaaa</a>
            <p>ppp</p>
            <div>div</div>
            <div id="impar"></div>
            <div id="par"></div>
            <div id="all"></div>

        </body>
    </html>

Javascript var elems = document.body.innerText; var odd = ""; var even = ""; var all = ""; for (k in elems){ all = all + elems[k]; if (k % 2 === 0) { even = (even + elems[k]).trim(); } else { odd = (odd + elems[k]).trim(); } }

                console.log(all);
                console.log(odd);
                console.log(even);

Hope this is helpful

Comments