简体   繁体   中英

How can I use inline style with data attribute using JavaScript no jQuery

I can use in my html file like this

<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.

To get the data-width from each element we can use getAttribute method.

Edit: You can select multiple elements like section , h1 , span in the same querySelectorAll

Live Demo: Using only 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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