3

I have following 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 specific <span>, its background color should be changed. i.e. if I click on span having id='select3', its background-color should be changed.

How this can be done using jQuery?

1
  • 1
    Attach a click handler to the spans in which you change the background color. What exactly do you need to know? What have you tried? Commented Feb 24, 2011 at 11:02

4 Answers 4

8

Try this one :

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

what it does is, clicking the span inside li having id starting with 'select' changes the backgound color.

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

Comments

1

You can use the following

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

Hope it helps.

Update my answer to put handler on each select. You can add some attr to your span elements to represent color. e.g. <span rel="red">Text</span>. And then you can write handler like

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

2 Comments

This will only add the click handler to the first element. Converting this to apply to multiple elements should be easy but you should mention it.
yes, here the #no of <LI>s will be dynamic. then what should I do?
0

Try

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

2 Comments

theres probably a way to combine the if statement into the selector, but i don't do much jQuery
Not only there are no select elements, but : should , in the css method.
0

If you have many list elements, you may want to use event delegation and only manage a click on the 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
    }
});

Comments

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.