How to Loop Through an HTML Table of URLs in JavaScript

Learn how to loop through a table of URLs and put the URLs into an array of strings using JavaScript.

This piece of code loops through a table of URLs on a sitemap. It turns the table of URLs into an array of strings of the URLs:

const url_table = document.getElementById("sitemap").rows

var post_urls = [];

for (let i = 0; i < url_table.length; i++) {
    post_urls.push(url_table[i].cells[0].innerText);
}

Background

Recently, I worked on a project related to analyzing each post on this site. To do this, I needed to obtain a collection of all URLs on this web page.

Google ranks websites with the help of sitemaps. Each website has one.

It can usually be found behind a URL like this:

https://<url.to.the.site>/sitemap.xml

OR

https://<url.to.the.site>/sitemap_index.xml

My sitemap for blog posts can be found at https://www.codingem.com/post-sitemap.xml.

My sitemap looks like this:

It is nothing but a basic HTML table that contains URLs and some other data.

Now, to grab the URLs from this table and put them into an array, I ran this piece of code in the JS console of the sitemap’s web page.

const url_table = document.getElementById("sitemap").rows

var post_urls = [];

for (let i = 0; i < url_table.length; i++) {
    post_urls.push(url_table[i].cells[0].innerText);
}

The url_table[i].cells[0] is an anchor tag (<a href>) with a URL. To grab the URL string from it, just call the .innerText property.

Now all the URLs are in an array. This makes it possible to easily perform an action for each URL there is.

Conclusion

I hope this short guide helps you save time if you are want to loop through an HTML table of URLs

Thanks for reading. I hope you find it useful.

Happy coding!

Further Reading

100 JavaScript Interview Questions

50 Buzzwords of Web Development

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest