Darth Vader Darth Vader - 1 year ago 44
Javascript Question

Extract Links Data and reformat them into a table

I would like to know if it is possible to extract a href data from a website page and input it into a table using jQuery. My clients usually want me to take a bunch links from their old sites and bring them into my CMS. If there is a way to put these links into a spreadsheet, then I can easily import them into my CMS system.

Here is an example of a link directory:

<div class="group">
<h1>Header 1</h1>
<ul>
<li><a href="http://link.com">Link Name A</a>
</li>

</ul>

</div>
<div class="group">
<h1>Header 2</h1>
<ul>
<li><a href="http://link.com">Link Name A</a>
</li>

</ul>

</div>


The script would take the header, the link name, and the url and reformat it like the following:

<table>
<thead>

<td>Link Name</td>
<td>Url</td>
<td>Category</td>

</thead>
<tbody>
<tr>
<td>Link Name A</td>
<td>http://link.com</td>
<td>Header 1</td>

</tr>
<tr>
<td>Link Name A</td>
<td>http://link.com</td>
<td>Header2</td>

</tr>

</tbody>
</table>

Answer Source

Well, there are other ways, but this will do what you ask based on the structure you provided. If the HTML structure is different, you will need to adjust:

 $(".group h1").each(function(){
    //loop though each h1
    //get h1
    var head = $(this).html()

    //get the li element
    var linkEl = $(this).next('ul').find('li')

    //get link text
    var linkTxt = linkEl.find('a').text()

    //get link url
    var linkURL = linkEl.find('a').attr('href')

    //add them to the table
    $("tbody").append("<tr><td>"+linkTxt+"</td><td>"+linkURL+"</td><td>"+head+"</td></tr>")
})

Fiddle: https://jsfiddle.net/x040mx73/1/