Timothy's Dev Stuff

A collection of code snippets and other developer things.

Extract Links from the Page

The code below can be used to extract all links and their text from a page. The extracted data is then converted to a <table> element. Once the table is compiled, a new window opens to display the table.
var x = document.querySelectorAll("a");
var myarray = []

for (var i = 0; i < x.length; i++) {
    var nametext = x[i].textContent;
    var cleantext = nametext.replace(/\s+/g, ' ').trim();
    var cleanlink = x[i].href;
    myarray.push([cleantext, cleanlink]);
};

function make_table() {
    var table = '<table><thead><th>Name</th><th>Links</th></thead><tbody>';
    for (var i = 0; i < myarray.length; i++) {
        table += '<tr><td>' + myarray[i][0] + '</td><td>' + myarray[i][1] + '</td></tr>';
    };

    table += '</tbody></table>';

    var w = window.open("");
    w.document.write(table);
}

make_table();