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;
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.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With