首页 > 解决方案 > 根据元素 ID 从数据部分获取值

问题描述

我想在页脚部分的 h2 中动态呈现部分 id="zero" 数据部分。由于我所有的页面都有不同的数据部分值,我希望我们可以定位部分 id="zero"。这样我就可以在我的网站上只使用一个页脚。我只是不精通 javascript 或 jQuery 来正确分配和调用。我知道有 document.getElementById('zero') 但是从数据部分获取值并让它出现在我的 H2 中我不清楚。

<section id="zero" class="section-wrap" data-section="Page Name"></section>

<section id="footer">
<h2></h2>
</section>

标签: javascriptjquerycustom-data-attribute

解决方案


这是一些应该有所帮助的Javascript。

//Get the data-section value
let val = document.getElementById('zero').dataset.section; 

//find the first h2 inside footer section
let header = document.getElementById('footer').getElementsByTagName("h2")[0];

//set the value
header.textContent = val; 

推荐阅读