I have the following html and am stumped as to how to read the contents of the href tag?
<p class="xyz-title">
<a href="">
<span class="field-content">Title here</span>
</a>
</p>
I tried document.getElementByClass('xyz-title')[0].innerHTML
but that didn't work obviously.
Thanks very much for pointing me in the right direction.
I have the following html and am stumped as to how to read the contents of the href tag?
<p class="xyz-title">
<a href="http://www.youtube./embed/xyz">
<span class="field-content">Title here</span>
</a>
</p>
I tried document.getElementByClass('xyz-title')[0].innerHTML
but that didn't work obviously.
Thanks very much for pointing me in the right direction.
Share Improve this question edited May 23, 2013 at 8:03 user1823761 asked May 23, 2013 at 7:55 BrokenCodeBrokenCode 9614 gold badges20 silver badges49 bronze badges3 Answers
Reset to default 6It is a syntax error. It is supposed to be getElementsByClassName
. Use this instead:
document.getElementsByClassName('xyz-title')[0].innerHTML
And for selecting the <a>
tag inside the <p class="xyz-title">
You need to use this code:
document.getElementsByClassName('xyz-title')[0].children[0].href
document.getElementsByClassName('xyz-title')[0].getElementsByTagName('a')[0].href
Or, you can simply use:
document.getElementsByTagName('a')[0].href
Fiddle: http://jsfiddle/praveenscience/DZhRv/
.innerHTML
will give you the content of the element, not the value of any attributes. .href
will give you the href
value.
You tried to use getElementByClass()
by there is no such function - you want getElementsByClassName()
(as per the tag that you added to the question), a function that returns a list so you do need the [0]
to get the first one.
To select the anchor element, try:
document.getElementsByClassName('xyz-title')[0].getElementsByTagName('a')[0].href
Or, simpler:
document.querySelector('.xyz-title a').href
Demo: http://jsfiddle/6Pg43/
Note that either way will give an error if the elements don't exist.
Working FIDDLE Demo
Try this:
var href = document.getElementsByClassName('xyz-title')[0].getElementsByTagName('a')[0].href;
alert(href);