Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can get the text of a div tag using only javascript (no jQuery)

I tried this but showing "undefined".

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

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

like image 998
agurchand Avatar asked Apr 29 '12 06:04

agurchand


People also ask

How do I get text inside a div?

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.

How do I get text inside a div using jQuery?

To get the value of div content in jQuery, use the text() method. The text( ) method gets the combined text contents of all matched elements. This method works for both on XML and XHTML documents.

How do I get text in JavaScript?

Use the textContent property to get the text of an html element, e.g. const text = box. textContent . The textContent property returns the text content of the element and its descendants. If the element is empty, an empty string is returned.

Can DIV tag have text?

Yes, you can directly add content text into a div tag, although using p tags would be preferable in most circumstances.


1 Answers

You'll probably want to try textContent instead of innerHTML.

Given innerHTML will return DOM content as a String and not exclusively the "text" in the div. It's fine if you know that your div contains only text but not suitable if every use case. For those cases, you'll probably have to use textContent instead of innerHTML

For example, considering the following markup:

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

You'll 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:

  • textContent
  • innerHTML
like image 95
dhar Avatar answered Oct 02 '22 16:10

dhar