codice:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .test1 { position: relative; display: flex; align-items: center; flex-wrap: nowrap } .test2 { background-color: red; color: blue; } </style> </head> <body> <div id="kilo"></div> <div class="kilo"></div> <div class="kilo"></div> <div id="mega"></div> <div class="mega"></div> <div class="mega"></div> <div id="giga"></div> <div class="giga"></div> <div class="giga"></div> <script> const kiloID = document.getElementById('kilo') const kiloClass = document.getElementsByClassName('kilo') const megaID = document.getElementById('mega') const megaClass = document.getElementsByClassName('mega') const gigaID = document.getElementById('giga') const gigaClass = document.getElementsByClassName('giga') const attributes1 = { 'position': 'relative', 'display': 'flex', 'align-items': 'center', 'flex-wrap': 'nowrap' } const attributes2 = { 'background-color': 'red', 'color': 'blue' } //////////////////////////////////////// metodo 1 const setElement = (el, attr) => { Object.keys(attr).forEach(k => { el.style[k] = attr[k] }) } const setAttributes = (el, attr) => { if (el.length > 0) { Array.from(el).forEach(classEl => { setElement(classEl, attr) }) } else { setElement(el, attr) } } setAttributes(kiloID, attributes1) setAttributes(kiloID, attributes2) setAttributes(kiloClass, attributes2) //////////////////////////////////////// metodo 2 const setEl = (el, attr) => { let mystyle = '' Object.keys(attr).forEach(k => { mystyle += `${k}:${attr[k]};` }) el.setAttribute('style', mystyle) } const setAttr = (el, attr) => { if (el.length > 0) { Array.from(el).forEach(classEl => { setEl(classEl, attr) }) } else { setEl(el, attr) } } setAttr(megaID, attributes1) // setAttr(megaID, attributes2) setAttr(megaClass, attributes2) /////////////////////////////////////// metodo 3 gigaID.classList.add('test1') gigaID.classList.add('test2') Array.from(gigaClass).forEach(el => { el.classList.add('test2') }) </script> </body> </html>

Rispondi quotando