Search code examples
javascripthrefgetelementsbyclassname

How to read the contents of a href with javascript?


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.com/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.


Solution

  • It 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.net/praveenscience/DZhRv/