I want to know how can I change all list item color or style with a button using Java Script ?
For example I have following unordered list in my HTML file:
<ul id="list">
<li> Item 1 </li>
<li> Item 2 </li>
<li> Item 3 </li>
</ul>
and a button in my HTML file:
<button type="button" id="btn"> Click to change all item colors black </button>
Now when I click on the button it should change the color of all the list items to black from one single click.Example of screenshot below 🙂
4
Answers
Add an event listener to the button that reacts to the click event.
and in the click event callback function write the logic to style the lists
A code that will change the color of all
li
elements under the id=list
when the button is clicked, I hope it will be useful.You can loop through each element and apply style to each element
Why haven’t you assigned any
id
orclass
attributes to the<li>
elements so that you could have differentiated which ones you have to work with?Considering these are the only
li
tags in your HTML page, you can write a function that gets these elements from JavaScript DOM and assign color attributes to the element.In order to get all elements with tag
li
, we have thegetElementsByTagName()
method.Also, I have just added few colors to the
li
items myself in your HTML code so as to initially see the items in different color.(Because I don’t know how you are getting different colors in the items)Your HTML Code=>
The JavaScript function that does the job=>
You may have to put this JavaScript code within
<script>
tags or in another.js
file which you have linked with this HTML page.Now, you can change the color to whatever you wanted and reuse the method for different colors.
Thanks.