Skip to content Skip to sidebar Skip to footer

Getting A Html H1 Value To Javascript Variable

If I wanted the value of a title that is going to be assigned to a header(h3) to become a javascript variable to bring information out of the local storage on a specific entry, how

Solution 1:

It really depends on your use-case what would be the best way to do that, and if you provide a little more code, the community might be better positioned to help you. In general, you can access the content of the first h3 tag by using:

document.getElementsByTagName('h3')[0].innerHTML

or if your tag has an id so you can use the below one

document.getElementById('yourId').innerHTML

or, if you have access to jQuery: $('h3').text()

Solution 2:

You can retrieve it like this. But be careful with index of the h3 element if you have multiple h3

var name = document.getElementById('name').innerHTMLconsole.log(name)
<h3id="name">Country_Name</h3>

Solution 3:

I would use textContent instead of innerHTML as it would be better performance wise.

var name = document.getElementById("myID").textContent

or by tag:

var name = document.getElementsByTagName('h3')[0].textContent

And if you want to see it in the console:

console.log(name)

Post a Comment for "Getting A Html H1 Value To Javascript Variable"