JSFiddle - React, Tailwind, and code Playground
by saltcod
HTML
<ol>
<li><a href="#" class="on"> A</a> </li>
<li><a href="#"> B</a> </li>
<li><a href="#"> C</a> </li>
</ol>
<p>How can I addClass of yellow to <strong>just</strong> the li containing the link I've clicked on? </p>
CSS
p {margin: 1em 0; } strong {font-weight: bold }
ol {width: 125px;background: #eee; }
li { padding: 10px; border-bottom: 1px solid;}
.on {background: #ccc; }
.yellow {background: #fffff0;
JavaScript
$("li a").click(function(e){
//stop browser default
e.preventDefault();
//remove on states for all nav links
$("li a").removeClass("on");
//add on state to selected nav link
$(this).addClass("on");
//set the LI background to yellow
if ( $('li a').hasClass('on') ){
$('li a').parent().addClass('yellow');
}
// All the li's don't have a class of 'on', but yet they all turn yellow.
});