How to get div tag text using only javascript (without jQuery)

I tried this but showed "undefined".

function test() { var t = document.getElementById('superman').value; alert(t); } 

Is there a way to get the value using simple Javascript no jQuery Please!

+64
javascript html
Apr 29 '12 at 6:28
source share
3 answers

You probably want to try textContent instead of innerHTML .

This innerHTML will return the contents of the DOM as a String , not just text in a div . This is good if you know that your div contains only text, but does not fit if each use case. For these cases, you probably have to use textContent instead of innerHTML

For example, given the following markup:

 <div id="test"> Some <span class="foo">sample</span> text. </div> 

You will get the following result:

 var node = document.getElementById('test'), htmlContent = node.innerHTML, // htmlContent = "Some <span class="foo">sample</span> text." textContent = node.textContent; // textContent = "Some sample text." 

See MDN for more details:

+121
Apr 29 '12 at 11:30
source share

Since textContent not supported in IE8 and textContent , this is a workaround:

 var node = document.getElementById('test'), var text = node.textContent || node.innerText; alert(text); 

innerText works in IE.

+6
Nov 09 '16 at 15:51
source share

You can use innerHTML (then parse text from HTML) or use innerText .

 let textContentWithHTMLTags = document.querySelector('div').innerHTML; let textContent = document.querySelector('div').innerText; console.log(textContentWithHTMLTags, textContent); 

innerHTML and innerText supported by all browsers (except FireFox <44), including IE6 .

0
Dec 07 '18 at 12:56
source share



All Articles