NuzzeSicK
NuzzeSicK

Reputation: 707

Variable equal to text inside element

I wanna know if is possible to declare a variable and be equal to the text inside an element, for example:

<p id="demo">Hi</p>

And then, declare a variable named demo = "Hi".

Thanks!

Upvotes: 0

Views: 1301

Answers (4)

Mariusz
Mariusz

Reputation: 361

I think you might want to use textContent on the element instead as it doesn't force page reflow.

textContent returns every element in the node.
In contrast, innerText is aware of styling and won’t return the text of “hidden” elements.
Moreover, since innerText takes CSS styles into account, reading the value of innerText triggers a reflow to ensure up-to-date computed styles.
(Reflows can be computationally expensive, and thus should be avoided when possible.)

So you should do something around those lines:
const demoText = document.getElementById("demo").textContent
const demoText = document.querySelector("#demo").textContent

Upvotes: 3

Nilanka Manoj
Nilanka Manoj

Reputation: 3718

try :

window.onload = () => {
    const val = document.querySelector('#demo').innerText;
    console.log(val)
}
<div id="demo">Hi</div>

Upvotes: 1

Hien Nguyen
Hien Nguyen

Reputation: 18975

You can use getElementById as

var demo = document.getElementById("demo").innerText;

Note that you need add script tag before close body tag not in head tag.

var demo = document.getElementById("demo").innerText;
console.log(demo)
<p id="demo">Hi</p>

Upvotes: 1

Zachary Haber
Zachary Haber

Reputation: 11027

Just use document.getElementById or document.querySelector

const demo = document.querySelector('#demo').innerText;

console.log(demo)
<div id="demo">Hi</div>

Upvotes: 1

Related Questions