How to read the contents of a href with javascript?

旧巷老猫 提交于 2021-01-24 18:59:26

问题


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.


回答1:


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/




回答2:


.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.net/6Pg43/

Note that either way will give an error if the elements don't exist.




回答3:


Working FIDDLE Demo

Try this:

var href = document.getElementsByClassName('xyz-title')[0].getElementsByTagName('a')[0].href;
alert(href);


来源:https://stackoverflow.com/questions/16708509/how-to-read-the-contents-of-a-href-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!