SimonRH SimonRH - 20 days ago 6
CSS Question

How to select a row that has been clicked

I want have a list of items in which the color of a selected element turns red when it is selected and all of the other divs turn blue. How can I identify the selected div that would then turn red?



$(document).ready(function() {
$('#table_1 .tableRow div').click(function(event) {

//Set the style for all divs
var myElements = document.querySelectorAll("#table_1 .tableRow div");
for (var i = 0; i < myElements.length; i++) {
myElements[i].className = "blueText";
}
//Set the style for tyhe selected div
//selectedItem.className="selectedText";
});
});

.selectedText {
color: red;
}
.blueText {
color: blue;
}

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>

<body>

<div id="table_1" class="table">
<div class="tableRow">
<div>
Line 1
</div>
<div>
Line 2
</div>
<div>
Line 3
</div>
</div>
</div>
</body>

</html>




Answer

It's enough to change:

//selectedItem.className="selectedText";

to:

event.target.className="selectedText";

The snippet:

$(document).ready(function(){
  $('#table_1 .tableRow div').click(function(event) {

    //Set the style for all divs
    var myElements = document.querySelectorAll("#table_1 .tableRow div");
    for (var i = 0; i < myElements.length; i++) {
      myElements[i].className="blueText";
    }
    //Set the style for tyhe selected div
    event.target.className="selectedText";
  });
});
.selectedText {
  color: red;
}
.blueText {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div  id="table_1" class="table">
    <div class="tableRow">
        <div>
            Line 1
        </div>
        <div >
            Line 2
        </div>
        <div >
            Line 3
        </div>
    </div>
</div>

Comments