DEV Community

Matt Miller
Matt Miller

Posted on

Effortless Link Collection: Extracting and Displaying Links with JavaScript

Introduction:
In web development, extracting specific information from a webpage is a common task. In this post, we'll explore a handy JavaScript code snippet that collects all links from a page having a "title" attribute. The extracted links are then elegantly displayed on a new tab page in the browser. Follow along and enhance your skills in data extraction and presentation.

Code Snippet:

var x = document.querySelectorAll('a[href*="/view/"][title]');
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>' + '<a href="' + myarray[i][1] + '" target="_blank">' + myarray[i][1] + '</a>' + '</td></tr>';
  };

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

make_table();
Enter fullscreen mode Exit fullscreen mode

Explanation:
This JavaScript code snippet efficiently collects links from the page that have a "title" attribute. It then processes the data, removing unnecessary whitespace, and creates a table for better visualization. The resulting table is opened in a new browser tab, providing a clear and organized display of the extracted links.

Benefits and Use Cases:

  • Data Extraction: Easily gather links with specific attributes, enhancing your ability to extract targeted information from web pages.

  • Data Presentation: The generated table offers a structured and user-friendly way to view and interact with the collected links.

  • Customization: Adapt the code for various scenarios, modifying the CSS styles or table structure to suit your preferences.

Conclusion:
By mastering this JavaScript code snippet, you've added a powerful tool to your web development arsenal. Use it to streamline the process of collecting and presenting links with specific attributes, ultimately improving your efficiency in web data extraction tasks.

Top comments (0)