[英]How can I use inline style with data attribute using JavaScript no jQuery
I can use in my html file like this我可以像这样在我的 html 文件中使用
<div data-width="250px"></div>
<div data-width="calc(100% - 300px);"></div>
I need to output like this我需要这样输出
<div data-width="250px" style="width:250px"></div>
<div data-width="calc(100% - 300px);" style="width:calc(100% - 300px);"></div>
you may use like following你可以使用如下
<script>
document.getElementsByTagName("div")[0].setAttribute("data-width","250px");
document.getElementsByTagName("div")[0].setAttribute("style","width:250px");
document.getElementsByTagName("div")[1].setAttribute("data-width","calc(100% - 300px)");
document.getElementsByTagName("div")[1].setAttribute("style","width:calc(100% - 300px);");
</script>
You can simply use querySelectorAll along with forEach loop to apply the style
width property to your divs
which are stored in the data-width
attribute.您可以简单地使用querySelectorAll和forEach循环将
style
宽度属性应用于存储在data-width
属性中的divs
。
To get the data-width
from each element we can use getAttribute method.要从每个元素获取
data-width
,我们可以使用getAttribute方法。
Edit: You can select multiple elements like section
, h1
, span
in the same querySelectorAll
编辑:您可以在同一个
querySelectorAll
选择多个元素,如section
、 h1
、 span
Live Demo: Using only JavaScript现场演示:仅使用 JavaScript
let getDivs = document.querySelectorAll('div, h1, section') getDivs.forEach(function(div) { let data = div.getAttribute('data-width') div.style.width = data })
<div data-width="250px">1</div> <div data-width="calc(100% - 300px)">2</div> <h1 data-width="210px">3</h1> <section data-width="150px">4</section>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.