javascript 获取 div 中的链接文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10539299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:12:32  来源:igfitidea点击:

Getting link text within a div

javascripthtml

提问by Gigazelle

I currently have an href that I'd like to pull text from. Unfortunately I don't have access to to code, and the limited code I have to work with is the following:

我目前有一个我想从中提取文本的 href。不幸的是,我无法访问代码,我必须使用的有限代码如下:

<div id="myDiv">
  <h1 class="myClass">
    <a href="link">TEXT</a>
  </h1>
</div>

I'd prefer using JavaScript to obtain this information. What would be the best way to reference 'TEXT'? I've tried a couple methods using getElementByIdand getElementsByClassName, but each have proven unsuccessful. Thanks!

我更喜欢使用 JavaScript 来获取这些信息。引用“文本”的最佳方式是什么?我尝试了几种使用getElementById和 的方法getElementsByClassName,但都证明都没有成功。谢谢!

回答by gdoron is supporting Monica

var text = document.getElementById('myDiv')
                   .getElementsByTagName('a')[0].innerHTML;
alert(text);? // TEXT

Live DEMO

现场演示

If you can use jQuery...:

如果您可以使用 jQuery...:

var text = $('#myDiv .myClass a').text();

回答by Etienne Dupuis

Can you use jQuery?

你会使用 jQuery 吗?

It would be

这将是

$(".myClass a").text();

Im not sure in plain javascript. That is why I am asking.

我不确定在纯 javascript 中。这就是为什么我要问。

回答by Imp

var links = document.getElementsByTagName('a');

for (var i = 0; i < links.length; i++)
    console.log('Link ' + i + ' text: ' + links[i].innerHTML);

回答by jbabey

Assuming you can't modify the HTML:

假设您无法修改 HTML:

http://jsfiddle.net/9rXaS/

http://jsfiddle.net/9rXaS/

document.getElementsByClassName('myClass')[0].childNodes[1].innerHTML;