'Is there any way that I can use variables while changing the the properties of document.getElemtentbyId(").style in JavaScript?

Is there any way that I can change the properties in document.getElementbyId.style with a variable that I received from the Parameters of the function?

function toggleFunction(elementId, property1, property2) {
    let element = document.getElementById(elementId)
    if (element.style.display == property1) {
        element.style.display = property2
    } else {
        element.style.display = property1
    }
}

The above code is not giving me the desired result. Is there a way that I can use variable values that I got from parameters for writing Properties?



Solution 1:[1]

Maybe I didn't catch what you need but its simple. Your code should work good if you use correct arguments for you func. But don't use "element" name twice. That is bad practise

const elementId = 'your-element-id'
const property1 = 'none'
const property2 = 'block'

const element = document.getElementById(elementId)
element.style.display = property1 // Set element's display = 'none'

The same way for another style properties:

element.style.width = '50%'
element.style.color = '#ff0000'
element.style.marginTop = '14px'

Read more -> HTML DOM Style Object

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vlad Krutenyuk