I am trying to use JavaScript to dynamically change the right margin for a horizontal list. I have created a variable called "space" that equals the margin quantity that I want. Now I need to make the right margin for each list item equal to the "space" variable.
To be more specific, I'm having trouble with how to reference the list items within my JavaScript file. I can reference elements by class and id using getElementsByClassName
and getElementById
, respectively, but I really need to refer to an <a>
link within a class. That is, in css I could manually modify the margin with:
.menu-item a {
margin: 0 50px 0 0;
}
Notice I need the "a" in the css selector reference. How do I get this reference into Javascript?
Here is some html:
<div class="container" id="container">
<ul>
<li class="menu-item" id="menuItem"><a href="item0.html">Item 0</a></li>
<li class="menu-item" id="menuItem"><a href="item1.html">Item 1</a></li>
<li class="menu-item" id="menuItem"><a href="item2.html">Item 2</a></li>
<li class="menu-item" id="menuItem"><a href="item3.html">Item 3</a></li>
<li class="menu-item" id="menuItem"><a href="item4.html">Item 4</a></li>
<li class="menu-item" id="menuItem"><a href="item5.html">Item 5</a></li>
</ul>
</div>
And here is some css:
.container{
width:auto;
margin-left:10%;
margin-right: 10%;
}
.menu-item a {
color: #000000;
font-family: sans-serif;
font-size: 16px;
float:left;
}
And here is some javascript:
var space = (document.getElementById("container").offsetWidth - 450)/6;
var menuItem = document.getElementsByClassName("menu-item"); /*this line is the problem*/
spacer();
function spacer () {
menuItem.style.margin = "0 " + space + "px 0 0"; /*and this line is potentially incorrect as well*/
}
As requested, I will take this opportunity to mention that I am after a solution that is compatible with all browsers. Thanks