如何从具有多个标签的innerhtml获取href?

时间:2019-04-23 20:50:16

标签: javascript html

是否可以访问innerHTML中特定标记的内容? 我有一个div标签,可以通过document.getelementbyclass()访问。它内有嵌套标签,并希望从其中一个嵌套标签中提取href。从下面的示例中获取链接的最佳方法是什么?

<div class="MyClass">
    <h5> Some text I dont want </h5>
    <a href="http://IwantThisLink.com"> http://IwantThisLink.com </a>
</div>

4 个答案:

答案 0 :(得分:2)

您也可以使用querySelector

document.querySelector('.MyClass a').getAttribute('href');

答案 1 :(得分:1)

这应该按照您的要求进行。

document.getElementsByClassName('MyClass')[0].getElementsByTagName('a')[0].href

请注意getElementsByClassNamegetElementsByTagName。他们将始终返回HTML标签的集合(数组),即使该集合只有一项。使用[0]访问数组将为您提供第一项。如果还有其他具有“ MyClass”类的元素,则只能选择第一个。这可能会导致某些意外行为。

如果某些重要的东西足以被JavaScript访问,则可能应该给它一个id属性,并使用getElementById对其进行访问。例如:

<div class="my-class">
    <h5> Some text I dont want </h5>
    <a id="important-link" href="http://IwantThisLink.com"> http://IwantThisLink.com </a>
</div>
document.getElementById('search').href

答案 2 :(得分:0)

已更新

document.querySelector('.MyClass a').setAttribute('href', 'google.com');

答案 3 :(得分:-1)

如果需要,可以使用Vanilla JS进行JQuery的短调用。

alert($(".MyClass a").attr("href"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="MyClass">
    <h5> Some text I dont want </h5>
    <a href="http://IwantThisLink.com"> http://IwantThisLink.com </a>
</div>