0

I've got problem with getting this text from href. I'm working on dom and I'd like to get text from this href:

<div class='xx'>
  <a href='zz' class='button>
...

I was trying to do sth like that:

document.getElementById(".xx").getAttribute("href")

But it's not working properly

Samanta
  • 11
  • 1
  • 1
  • the href is another element, not an attribute. And ".xx" is a class selector, not an id selector. And what text? There's no text shown in your example. I suggest you take a beginner tutorial, because this looks like guesswork. – ADyson Dec 19 '17 at 14:34
  • `xx` is a class not an ID. Read here: https://stackoverflow.com/questions/21436550/javascript-how-to-get-only-one-element-by-class-name/21436552 – Turnip Dec 19 '17 at 14:34
  • You are totally right! Comment deleted... – Tito Sanz Dec 19 '17 at 14:41

6 Answers6

3

But it's not working properly

Because

  • you don't have an element with id attribute .xx,
  • .xx targets the div not the anchor

Also, your anchor tag's attribute class is not closed properly, also closing tag is not given either.

<div class='xx'>
  <a href='zz' class='button'>Some text</a>
</div>

you have a class so use the class selector itself using querySelector

document.querySelector( ".xx .button" ).getAttribute( "href" )

or simply

document.querySelector( ".xx .button" ).href;
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
2

getElementById will grab an element by that ID. You have an anchor (malformed albeit) with not an ID but a class. Secondly you are targeting the parent div. You should be targeting the tag using querySelector() instead. Then to get the href you'd use href.

const href = document.querySelector('.xx .button').href;

console.log(href);
<div class='xx'>
  <a href='zz' class='button'></a>
</div>
Carl Edwards
  • 13,826
  • 11
  • 57
  • 119
1

The code below will get text from link:

var x = document.getElementsByClassName('xx')[0].getElementsByTagName("a")[0].getAttribute("href");
slon
  • 1,002
  • 1
  • 8
  • 12
1

This works for me

document.getElementsByClassName("xx")[0].getElementsByTagName("a")[0].getAttribute("href")
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Naveen
  • 31
  • 4
0

you can use id instead of class because class returns undefined value.and also you tried to get class using getby id

wrong:

document.getElementById(".xx").getAttribute("href")

function h()
{
alert(document.getElementById("button").href);
}
<a href='zz' id='button' onclick='h();'>
asd</a>
jasinth premkumar
  • 1,430
  • 1
  • 12
  • 22
0
var yourhref = document.querySelector("div.xx a.button").href

yourhref holds your requested value. This is as precise as it gets using only the part of code you provided. If somewhere else on the page you have a div with class xx and a link with class button you are not gonna have a good time.

Solution - either have your targeted element or parent have UNIQUE id and then write a selection from there.

DanteTheSmith
  • 2,937
  • 1
  • 16
  • 31