-1

I have group of unordered list. I have create some function that make every list is clicked, it will run a JS Function. Now I want to add some css, if the list is clicked, its bg color will changed. My code so far:

function getDealsTable(obj) {
        var tenor = obj.innerHTML;
        $(this).closest('li').css('background-color: rgba(86, 142, 175, 1) !important');
        $(this).closest('li').siblings('li').css('background-color: rgba(15, 86, 132, 1) !important');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class='tenors'>
    <li onclick='getDealsTable(this);'>12x</li>
    <li onclick='getDealsTable(this);'>24x</li>
    <li onclick='getDealsTable(this);'>36x</li>
    <li onclick='getDealsTable(this);'>48x</li>
</ul>

Unfortunately it doesn't works. I have tried to change it to a class, but still not working. Anyone can help me? Thanks

4
  • closest means traverse up the tree - you can't have a closest li unless it is a nested ul (as your click is bound to an li) Commented Mar 19, 2019 at 15:32
  • 'this' IS the li, so no need to do closest, try $(this).css('background-color: rgba(86, 142, 175, 1) !important'); Commented Mar 19, 2019 at 15:32
  • already tried to only $(this) but still not working Commented Mar 19, 2019 at 15:38
  • What do want to actually achieve? Also with sibling? Commented Mar 19, 2019 at 15:39

1 Answer 1

1

In order to use !important with jQuery, you need to have 2 parameters. The first parameter is cssText, the second is the text you want to set as explained here

Example:

$('.selector').css('cssText', 'color: red !important;')

You can also create the click event using on directly in the javascript, no need to place it on the html element.

$('ul.tenors > li').on('click', function() {
  // Reset all the li colors (must come first)
  $('ul.tenors > li').css('cssText','background-color: rgba(86, 142, 175, 1) !important;');
  // Set the color of the clicked li item (must come second)
  $(this).css('cssText', 'background-color: rgba(15, 86, 132, 1) !important;');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class='tenors'>
  <li>12x</li>
  <li>24x</li>
  <li>36x</li>
  <li>48x</li>
</ul>

Sign up to request clarification or add additional context in comments.

3 Comments

Perfect! But at your code, the color is reversed. But it's okay, I can handle it. Also thanks to remove that function to be just point it at its class. Thanks!
I added some comments to the js, just in case you need them.
Sure! Thanks for explanation... :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.