Reputation: 693
I am trying to get the text inside p tag
<p id="paragraph">Some text</p>
And i want to store the text in JavaScript variable like this
var text = "Some text";
I read that i have to add
var text = document.getElementById("paragraph").innerHtml;
But the value of the variable is NULL or Undefined and i did also like this
var text = document.getElementById("paragraph")[0].innerHtml;
And i had the same problem !
Upvotes: 14
Views: 25322
Reputation: 77482
In your example you are using incorrect property name, must be innerHTML
(note - case sensitivity HTML
not Html
) not innerHtml
var text = document.getElementById("paragraph").innerHTML
^^^^
Upvotes: 22
Reputation: 82277
You should probably use .textContent
to get the text to make sure you don't get extra markup in your text variable.
var paragraph = document.getElementById("paragraph");
var text = paragraph.textContent ? paragraph.textContent : paragraph.innerText;//IE uses innerText
innerHTML returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. textContent should be used instead. Because the text is not parsed as HTML, it's likely to have better performance. Moreover, this avoids an XSS attack vector.
https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent
Upvotes: 6
Reputation: 4896
var text = document.getElementById("paragraph").innerHTML;
Upvotes: 4