Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting the inner text of a node

Tags:

I am having trouble getting the inner text of a particular node. I have added the example node I am working with and the javascript I have come up with. The javascript works as far as returning this <span id="goal_left">3 goals lect</span> if i log it to the console. If i add innerText to the javascript examples it will return nothing to the console. Any ideas how to get this text?

html

<span id="goal_left">3 goals lect</span> 

javascript: these examples return <span id="goal_left">3 goals lect</span>

document.getElementById("goal_left");  document.querySelectorAll("span#goal_left")[0]; 

javascript: these examples return nothing

document.getElementById("goal_left").innerText;  document.querySelectorAll("span#goal_left")[0].innerText; 
like image 433
Daniel Avatar asked Jul 31 '12 17:07

Daniel


People also ask

How do I get the innerHTML value?

Firstly, to get the innerHTML value of any tag, you either need that tag to have its 'id' property or 'name' property set. Then you can respectively use the 'document. getElementById(yourTagIdValue). innerHTML' or 'document.

How do I get Div text?

Use the textContent property to get the text of a div element, e.g. const result = element. textContent . The textContent property will return the text content of the div and its descendants. If the element is empty, an empty string is returned.

How do I get inner text in jQuery?

Answer: Use the jQuery text() method You can simply use the jQuery text() method to get all the text content inside an element. The text() method also return the text content of child elements.


1 Answers

Probably the easiest way:

document.querySelectorAll("span#goal_left")[0].firstChild.nodeValue; 

Though if you always want the first node returned by querySelectorAll() you could simply use:

document.querySelector("span#goal_left").firstChild.nodeValue; 

Incidentally, I'd imagine any browser that implements querySelectorAll()probably implements textContent, giving:

document.querySelector("span#goal_left").textContent; 

Just to offer a cross-browser option:

var textProperty = 'textContent' in document ? 'textContent' : 'innerText'; document.getElementById('goal_left')[textProperty] 
like image 104
David Thomas Avatar answered Oct 01 '22 08:10

David Thomas