Scraping the actual attribute name from webpage?

Viewed 35

Apologies if this is basic but I can't seem to phrase my question to find the results elsewhere.

Basically, I am wondering how to webscrape the actual name of a CSS Attribute from a webpage using Javascript. Intuitively, I want to use document.querySelectorAll('a [title]'), but this is simply a selector to get the text content that is labeled with those selectors and doesn't scrape the actual title attribute's name itself.

In the below example, document.querySelectorAll('a [title]') would select "A Light in the..." body text, not "A Light in the Attic" meta title name.

<h3>
  <a href="catalogue/a-light-in-the-attic_1000/index.html" title="A Light in the Attic">A Light in the...</a>
</h3>

You can see why this is important, as I'm dealing with a webpage that cuts off the name when written in the body text but writes it out entirely in the title meta tag.

Thank you!

1 Answers

I have made two a solution. Getting the content of the title attribute of all a tags at once, and on click.

To get the content of the title attribute, you need to use getAttribute(). But since the collection of tags a is used, I decided to use the for loop.

let a = document.querySelectorAll('a');

for (var i = 0; i < a.length; i++) {
  console.log(a[i].getAttribute('title'));
}
<h3>
  <a href="" title="A Light in the Attic1">A Light in the...</a>
  <a href="" title="A Light in the Attic2">A Light in the...</a>
  <a href="" title="A Light in the Attic3">A Light in the...</a>
</h3>

The second solution, where to get the content of the title attribute on click:

let a = document.querySelectorAll('a');

for (var i = 0; i < a.length; i++) {
  a[i].onclick = function(event) {
    event.preventDefault();
    console.log(this.getAttribute('title'));
  }
}
<h3>
  <a href="" title="A Light in the Attic1">A Light in the...</a>
  <a href="" title="A Light in the Attic2">A Light in the...</a>
  <a href="" title="A Light in the Attic3">A Light in the...</a>
</h3>

Related