最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get Text of Nested Span HTML element? - Stack Overflow

programmeradmin2浏览0评论

I want to get text from Nested SPAN element in Following HTML code:

<span id='result_box'>
<span class="hps">text_content</span>
</span>

I want to get "text_content" value using JavaScript.

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

I want to get text from Nested SPAN element in Following HTML code:

<span id='result_box'>
<span class="hps">text_content</span>
</span>

I want to get "text_content" value using JavaScript.

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

Share Improve this question edited Dec 24, 2012 at 8:39 Ganpat asked Dec 24, 2012 at 7:32 GanpatGanpat 8633 gold badges17 silver badges34 bronze badges 2
  • What's your error? The code works fine in this jsfiddle: jsfiddle.net/Ralt/TrR62 – Florian Margaine Commented Dec 24, 2012 at 7:48
  • nothing to display but last Alert not showing. – Ganpat Commented Dec 24, 2012 at 7:51
Add a comment  | 

4 Answers 4

Reset to default 8

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.

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 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>

you get the element by classname.. document.getElementsByClassName() and then grabbing the first item off the resulting node list

window.onload = function () {
   document.getElementsByClassName("hps")[0].innerHTML
};     

jsfiddle

var resBox=document.getElementById('result_box');
var strTrans=document.getElementsByTagName('span')[0].innerText;
alert(strTrans);​

or better

strTrans = document.querySelector(".hps").innerText ;

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.

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.

it seems like bing also provides a api.i'm not sure.

发布评论

评论列表(0)

  1. 暂无评论