Question: I am busy writing a javascript/jquery based version of the game Battleship. In my overview-screen I have a list of games. What I would like to do, is that every time when I select (click on) a list-item, the background-color of the list-item changes and the selected item is saved in a variable and when I select another list-item that item will be selected and the background-color of the previous selected item will change back to normal. There is only one problem, I could not find an efficient way to change the background-color and save the list-item to a var. Currently I am trying to do it this way but that does not feel right.

```
this.setListenerForElementsInGameList = function() {
    $('#game-list li').each(function(){
        this.click(this.event_selectGameFromList);
    });
}

this.event_selectGameFromList = function() {
    $('#game-list li').each(function(){
        this.css("background-color", "#39B7CD");
    });
    this.css("background-color", "#FFFFFF")
}

```

Sadly it does not work yet, but I would like to hear if I am heading in the right direction with how my code is looking so far or if there is an easier, cleaner and more efficient way of doing it.

All help will be appreciated.

PS. This is the current layout of my game-overview: " <http://i.imgur.com/ujF6Ys9.png> "

Answer: 
You don't need to [`.each()`](http://api.jquery.com/each/) to bind event and use `.css()`. jQuery doest it for you. Also since `.css()` is a jQuery method you need to convert `this` into jQuery object.

```
this.setListenerForElementsInGameList = function() {
    $('#game-list li').click(this.event_selectGameFromList);
}

this.event_selectGameFromList = function() {
    $('#game-list li').css("background-color", "#39B7CD");

    //Here this refers to element which initiated the event
    $(this).css("background-color", "#FFFFFF")
}

```

*Note*: `this` in the function refers to element which you are iterating.
This is a better way to solve the problem, since using css classes is better than modifying css directly in javascript. Also you would be able to do more styling than just change the background for the selected item.

I have also modified some of the javascript eliminating unnecessary foreach loops.

```
this.setListenerForElementsInGameList = function() {
    $('#game-list li').on('click', this.event_selectGameFromList);
}

this.event_selectGameFromList = function(e) {
    var selected = $('selected');
    $('#game-list .selected').removeClass('selected');
    $(this).addClass('selected');
}

```

With following css:

```
.game-list li {
    list-style: none;
    background-color: #39B7CD;
}

.game-list .selected {
    background-color: #FFFFFF;
}

```

Here is the jsfiddle: <https://jsfiddle.net/pv1076f1/1/>