0

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
  • 1
    The whole point of classes is to apply styling to a class of elements so you don’t have to repeat yourself: inputHtmlDevice.classList.add(“one-class-to-rule-them-all”) Commented Sep 11, 2022 at 19:45

1 Answer 1

1

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')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.