简体   繁体   English

获取 HTML h1 值到 Javascript 变量

[英]Getting a HTML h1 value to Javascript variable

如果我希望将分配给 header(h3) 的标题的值成为一个 javascript 变量,以将信息从特定条目的本地存储中取出,我该怎么做?

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:通常,您可以使用以下方法访问第一个 h3 标签的内容:

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

or if your tag has an id so you can use the below one或者如果你的标签有一个 id,那么你可以使用下面的一个

document.getElementById('yourId').innerHTML

or, if you have access to jQuery: $('h3').text()或者,如果您可以访问 jQuery: $('h3').text()

You can retrieve it like this.您可以像这样检索它。 But be careful with index of the h3 element if you have multiple h3但是如果您有多个 h3,请注意 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.我会使用 textContent 而不是innerHTML,因为它会更好地提高性能。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM