How to correctly add CSS to input element through JavaScript

Viewed 38

I have an input field with the class 'device_1' which has a css style applied to it. The function 'createNewInputField()'created new input field with the class 'device_2'. Every new field creation creates a new class name. I want to apply the same CSS style applied to 'device_1' to the newly created fields ('device_2', ... , 'device_X'). I have a function 'addStyle()' that is supposed to do exactly this but it does not actually apply the style.

var idNumber= 1;
var deviceID = "device_"+idNumber;
var kWattID = "kW_"+idNumber;
var hoursID = "hours_"+idNumber;
var totalID = "total_"+idNumber;
        


function createNewInputFields() {

    idNumber = idNumber+1;
    deviceID = "device_"+idNumber;
    const containerDevice = document.getElementById('deviceCol');
    const inputHtmlDevice = "<br><input type='text' id='"+deviceID+"' required>";
    containerDevice.insertAdjacentHTML('beforeend', inputHtmlDevice);
    containerDevice.style(addStyle(containerDevice, idNumber));
    return idNumber;
}

function addStyle(container, number){
    var styles = `
    #device_`+number+`{
        text-align: center;
        border-radius: 10px;
        border:solid #2b2b2b;
        border-width: 2px;
    }
    `
    return styles
}
#device_1{
    text-align: center;
    border-radius: 10px;
    border:solid #2b2b2b;
    border-width: 2px;
}
<div class="calculationSection">
            <h1 class="energytitle">Energy calculations</h1>
            <div class="row_2">
                <div class="deviceCol" id="deviceCol">
                    <p><b>Device</b></p>
                    <input type="text" id="device_1" required>
            </div>
            <div class="addButton"> 
                <button class="btn" onclick="createNewInputFields()"> Add device </button>
            </div>
        </div>

1 Answers

The error says it loud and clear containerDevice.style is not a function. To add styles, you need to add them one at a time as properties, like

containerDevice.style.backgroundColor = '#000'

but it's far more efficient and better practice to create actual styles in your css for this and just add or remove them

css:

.elementcss {
    text-align: center;
    border-radius: 10px;
    border:solid #2b2b2b;
    border-width: 2px;
}

javscript:

document.querySelector('.element').classList.add('elementcss')
document.querySelector('.element').classList.remove('elementcss')
Related