admin管理员组

文章数量:1180494

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 !

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 !

Share Improve this question edited Dec 22, 2014 at 19:26 j08691 208k32 gold badges267 silver badges280 bronze badges asked Dec 22, 2014 at 19:24 MaroxtnMaroxtn 6934 gold badges8 silver badges15 bronze badges 0
Add a comment  | 

3 Answers 3

Reset to default 22

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
                                                     ^^^^

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

var text = document.getElementById("paragraph").innerHTML;

本文标签: htmlHow get the text inside a paragraph with JavaScriptStack Overflow