Jquery: onclick color change color

I have a UL-LI html.

<UL>
<LI><span id='select1'>Text</span></LI>
<LI><span id='select2'>Text</span></LI>
<LI><span id='select3'>Text</span></LI>
<LI><span id='select4'>Text</span></LI>
<LI><span id='select5'>Text</span></LI>
<LI><span id='select6'>Text</span></LI>
</UL>

If I click on a specific one <span>, its background color should be changed. that is, if I click on a range with id='select3', its background color should be changed.

How can this be done using jQuery?

+3
source share
4 answers

Try the following:

$('li span[id^="select"]').click(function(){
   $(this).css('background-color',"#ccc")
})

what it does is by clicking spaninside li, having an identifier starting with 'select' changes the background.

+5
source

You can use the following

jQuery("#select1").click(function(){jQuery(this).css({'background-color':'red})});

Hope this helps.

, . attr span . <span rel="red">Text</span>. ,

jQuery("ul span[id^='select']").click(function(){jQuery(this).css({'background-color':jQuery(this).attr('rel')})});
+1

Try

$("span").click(function(){
  if($(this).attr('id') == "select3") $(this).css('background-color', 'red');
});
0
source

If you have many list items, you can use event delegation and control only by clicking on ul. So you can do

$('ul').click(function(event) {
    switch($(event.target).attr('id')) {
        case select1:
            $(event.target).css('background-color', 'red');
            break;
        //More case statements
    }
});
0
source

Source: https://habr.com/ru/post/1794403/


All Articles