How to get HTML element Text of Nested Span?

I want to get text from a nested SPAN element in the following HTML:

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

I want to get the value of text_content using JavaScript.

I 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 on an online page enter image description hereenter image description here

+4
source share
4 answers

your code is working fine. I think your problem is that you are executing this code when the DOM does not load fully. If you are experiencing something, you can try it.

 window.onload = function () { //put your code here,it will alert when page loaded completely. }; 

or put a 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> 
+6
source

you get an element by the name of the class document.getElementsByClassName() , and then grab the first element from the resulting list node

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

jsfiddle

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

or better

 strTrans = document.querySelector(".hps").innerText ; 
+1
source

got you, I think you are embedding a link to your html page, then you want to manipulate the DOM on the page you are inserting, right? If so, you can check the policies of the same browser origin.

If you want to make an online translation through Google, you can google "google translate api", google provides api to others for implementing online translation in their applications.

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

+1
source

All Articles