Solution 1 :

You don’t need to set margin with the line:

hiddenList.style.margin= '300em';

since you already define the element with that margin in the CSS with:

.mylist{
    margin: 300em;
}

So just remove that.

The reason that was causing a problem is that the line of script was the equivalent of adding the following to the HTML:

<ul class="mylist" style="margin: 300em">

And with the rules of precedence in CSS being what they are, that inline style has a higher priority over that declared in the CSS.

See MDN’s article on CSS Specificity for more details.

Solution 2 :

Your problem is you fixed inline style by this line:

hiddenList.style.margin= '300em';

Then just remove it then everything works

let hiddenList= document.querySelector('.mylist');
let button= document.querySelector('button');

button.addEventListener('click', function(){
    console.log(hiddenList)
    hiddenList.classList.toggle('shown')
})
.mylist{
    margin: 300em;
}

.mylist.shown{
    margin: 2em;
}
<nav class="menu">
        <button>
            <h1>Menu</h1>
        </button>

        <ul class="mylist">
            <li>About</li>
            <li>Contact</li>
            <li>Services</li>
        </ul>
        
    </nav>

Problem :

I have an html menu with a button to open it and a unordered list :

 <nav class="menu">
        <button>
            <h1>Menu</h1>
        </button>

        <ul class="mylist">
            <li>About</li>
            <li>Contact</li>
            <li>Services</li>
        </ul>
        
    </nav>

I want to use javascript to alter the ul class to change its margin on click:
CSS:

.mylist{
    margin: 300em;
}

.mylist.shown{
    margin: 2em;
}

This script doesn’t function, can someone point out my problem, thank you

let hiddenList= document.querySelector('.mylist');
let button= document.querySelector('button');
hiddenList.style.margin= '300em';



button.addEventListener('click', function(){
    hiddenList.classList.toggle('shown')
})

Comments

Comment posted by Heretic Monkey

Don’t set the style in JavaScript (remove

Comment posted by David Thomas

Further to Heretic Monkey’s comment, the reason it’s taking precedence over the margin in your style-sheet is because

By