最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Getting a HTML h1 value to Javascript variable - Stack Overflow

programmeradmin2浏览0评论

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 page document.querySelectorAll("h3") will return all h3 elements in the page. both functions takes a CSS selector to decide what to select. – user128511 Commented Apr 10, 2017 at 16:46
Add a ment  | 

3 Answers 3

Reset to default 9

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 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)
发布评论

评论列表(0)

  1. 暂无评论