1

Let's say we have unknown number of div elements. When we click on the element that element must change its background color. How to do that without using classes or ids.

NOTE: I found some questions with similar topic but they were not what I was looking for.

I mean smth like:

$(element).click(
    function(){
       $(element).css("background-color","#DDDDDD");
    }
);

HTML:

<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

CSS:

div{
height:10px;
width:10px;
float:left;
border-radius:50%;
margin:2px;
background-color:#00A2E8;
}

DEMO

1

5 Answers 5

3

You are pretty close, just refer to the element itself in the function.

$("div").on("click",
    function(){
       $(this).css("background-color","#DDDDDD");
    }
);
Sign up to request clarification or add additional context in comments.

Comments

2

Like this?

$('div').click(function() {
  $(this).css('background-color', '#DDDDDD');
});

https://jsfiddle.net/ooyjLsy4/2/

Comments

1

You can use the "this" in jquery to accomplish what you are asking.

$('div').click(
    function(){
      $(this).css("background-color","{{Your Color}}");
    }
);

Comments

1

If you want to get all elements of a certain type, you can directly just use their names $('div'), $('a'), $('span'), etc.

If you have an event (click, mouseover, change, etc.), you can access to the specific control that fires that event by just using $(this) within that event block.

Therefore you should have this:

$('div').click(
    function(){
        $(this).css("background-color","#DDDDDD");
    }
);

Comments

0

What you're looking for is the element selector in jquery. Simply do $("div") to select all div elements. More information on selectors can be found at this page.

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.