0

I already learn how to alert element by tag.

 alert(document.querySelector("html")
.innerHTML);

I want to use alert by role. I dont know how to start this so I ask here for any idea. By the way. role="article"

1 Answers1

3

That would be attribute selection

const firstArticle = document.querySelector("[role=article]");
const allArticles  = document.querySelectorAll("[role=article]");

You can loop - here I convert to array using the ...spread operator because some of the earlier newer browsers do not have forEach on HTML collections

[...document.querySelectorAll("[role=article]")]
  .forEach(article => console.log(article.innerHTML));

Newest Chrome, Firefox and Edge can do

document.querySelectorAll("[role=article]")
  .forEach(article => console.log(article.innerHTML));

Note: forEach is somewhat slower than for, but is more readable. If you do not have thousands of articles on the page it will not matter. If you DO want to use for, then

mplungjan
  • 169,008
  • 28
  • 173
  • 236