How Can Get the Text of a Div Tag Using Only JavaScript (No Jquery)

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

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

JS: Extract text from a string without jQuery

Let the Browser do the sanitation and use this trick:

var str= '<article><img alt="Ice-cream" src=http://placehold.it/300x300g">'+
'<divstyle="float: right; width: 50px;"><p>Lorem Ipsum </p></div></article>';

var dummyNode = document.createElement('div'),
resultText = '';

dummyNode.innerHTML = str;
resultText = dummyNode.innerText || dummyNode.textContent;

This creates a dummy DOM element and sets its HTML content to the input string.

Now the only text can be got by simply calling the DOM property innerText or textContent.

This is also more safe and robust as Browser has already written better algorithms to get these values.

How to get div text value?

You can do it like this

alert(document.getElementsByClassName("question")[0].children[0].innerHTML);

How we can access a div from JavaScript?

You may want to use ....innerHTML

function fun(){
var a= document.getElementById("content").innerHTML;
console.log(a);

}
<div id="content">
<p>this is para</p>
</div>
<button onclick="fun()">show it</button>

how to get content in a div without specific child element

alert($("div.news").contents().not("figure.summary").text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><div class="news">     i need this content
<figure class="summary"> i dont need this content </figure>
</div>

How to change text inside a div without changing any other element in the div

With element.innerText() you're essentially overwriting the whole content of your div - including other html elements such as the anchor tag.

There's a child attached to your div that actually holds your text.
You can reference it via document.getElementById("title").firstChild along with it's .data property.