skip to Main Content

What is the best way to grab the href value from the anchor tag with the anchor tag has no id. It looks like this:

<a href="www.google.com">mydoc.pdf</a>

Usually I would use getElementById, but can’t in this case. I also tried getElementsByTagName, but since there are so many on the page it would be impossible.

2

Answers


  1. I think you do not have any other option than using the position (index) of the element:

    const el = document.getElementsByTagName('a')[1]; //second anchor element
    console.log(el.href);
    <a href="www.stackoverflow.com">stack overflow</a><br>
    <a href="www.google.com">mydoc.pdf</a><br>
    <a href="www.youtube.com">youtube</a>
    Login or Signup to reply.
  2. in this case, your tag not has any unique value to query like id, name, …
    if you know it’s index or "mydoc.pdf" you can get it.
    sample:
    var atags = document.getElementByTagName("a"); var selectedByIndex = atags[index]; var selectedbyText = atags.filter(function(tag,index) { return tag.innerHTML === "mydoc.pdf"; });

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search