Search code examples
javascriptarrayslistonclickgetelementsbytagname

Onclick event on an array of list items


I have a list and I want to create a function that will bold the clicked list item. So far I managed to create a function and assign it to list items. Onclick, it bolds, but just one item. I don't know how to set it for each item.

I could have used id to bold the items but there will be a lot of items in the list. I can't deal with each one of them.

html

<ul>
    <li>apple</li>
    <li>orange</li>
    <li>banana</li>
</ul>

javascript

var list = document.getElementsByTagName("li");

function markSelection() {
    if(list[0].style.fontWeight !== "bold") {
        list[0].style.fontWeight = "bold";
    } else {
        list[0].style.fontWeight = "normal";
    }
}

for (i = 0, len = list.length; i < len; i++){
    list[i].onclick = markSelection;
}

It bolds only list[0]. How can I set it to bold the clicked list item?

jsfiddle


Solution

  • function markSelection() {
        if(this.style.fontWeight !== "bold") {
            this.style.fontWeight = "bold";
        } else {
            this.style.fontWeight = "normal";
        }
    }
    
    for (i = 0, len = list.length; i < len; i++){
        list[i].onclick = markSelection;
    }