If I wanted the value of a title that is going to be assigned to a header(h3) to bee a javascript variable to bring information out of the local storage on a specific entry, how would I do that?
If I wanted the value of a title that is going to be assigned to a header(h3) to bee a javascript variable to bring information out of the local storage on a specific entry, how would I do that?
Share Improve this question asked Apr 10, 2017 at 16:33 JonathonJonathon 371 gold badge1 silver badge5 bronze badges 3- Using javascript, to create a variable with HTML, you must assign a id to the h1, and then create the var ( h1title = document.getElementById('h1title_id').innerHTML;) and its done. – Roy Bogado Commented Apr 10, 2017 at 16:35
- Could you please provide a code sample? – Kristian Oye Commented Apr 10, 2017 at 16:41
-
You don't need to assign an id.
document.querySelector("h3")
will return the first<h3>
element in the pagedocument.querySelectorAll("h3")
will return allh3
elements in the page. both functions takes a CSS selector to decide what to select. – user128511 Commented Apr 10, 2017 at 16:46
3 Answers
Reset to default 9It really depends on your use-case what would be the best way to do that, and if you provide a little more code, the munity 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()
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').innerHTML
console.log(name)
<h3 id="name">Country_Name</h3>
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)