javascript 如何获取嵌套 Span HTML 元素的文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14018470/
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
How to get Text of Nested Span HTML element?
提问by Ganpat
I want to get text from Nested SPAN element in Following HTML code:
我想从以下 HTML 代码中的嵌套 SPAN 元素中获取文本:
<span id='result_box'>
<span class="hps">text_content</span>
</span>
I want to get "text_content" value using JavaScript.
我想使用 JavaScript 获取“text_content”值。
I have tried this but have a problem:
我试过这个,但有一个问题:
var resBox=document.getElementById('result_box');
var strTrans=resBox.getElementsByTagName('span')[0].innerHTML;
alert(strTrans);
EDIT: Actually i want to do this from Online Page
编辑:其实我想从在线页面做到这一点
采纳答案by chris
your code works fine. i guess your problem is you are executing these code when DOM not loaded completely.if you are testing something, you can try this.
你的代码工作正常。我猜你的问题是当 DOM 没有完全加载时你正在执行这些代码。如果你正在测试一些东西,你可以试试这个。
window.onload = function () {
//put your code here,it will alert when page loaded completely.
};
or put the script after your span element. like this.
或将脚本放在 span 元素之后。像这样。
<span id='result_box'>
<span class="hps">text_content</span>
</span>
<script type='text/javascript'>
var resBox=document.getElementById('result_box');
var strTrans=resBox.getElementsByTagName('span')[0].innerHTML;
alert(strTrans);// it will alert
</script>
回答by bipen
回答by mpm
var resBox=document.getElementById('result_box');
var strTrans=document.getElementsByTagName('span')[0].innerText;
alert(strTrans);?
or better
或更好
strTrans = document.querySelector(".hps").innerText ;
回答by chris
got you, i guess you embed a link in your html page,then you wanna manipulate DOM in the page you embed,right? if so, you can check browser same origin policy.
明白了,我猜你在 html 页面中嵌入了一个链接,然后你想在你嵌入的页面中操作 DOM,对吗?如果是这样,您可以检查浏览器同源策略。
if you wanna implement online translation via google, you can google 'google translate api', google provides a api to others for implementing online translation in their own applications.
如果你想通过谷歌实现在线翻译,你可以谷歌“谷歌翻译api”,谷歌为其他人提供了一个api,用于在他们自己的应用程序中实现在线翻译。
it seems like bing also provides a api.i'm not sure.
似乎 bing 也提供了一个 api。我不确定。