Malcolm
Malcolm

Reputation: 12864

Use JQuery to get the index of a div with a specified background color

I have a div that contains a number of divs inside it. The divs are used to select a number by the user. When the select a div I make the background color of that div to green.

My problem is how do I write a JQuery selector to give me the index of the div that is selected ie green?

Malcolm

EDIT

var green = "rgb(0, 128, 0)";

function getIndex(selector) {
$(selector).each(function () {
    if ($(this).css("background-color") == green)
        return $(this).index();
});
return -1;

}

Upvotes: 0

Views: 90

Answers (6)

Tuhin
Tuhin

Reputation: 3373

I think this is what you need.

HTML

<div class="container">
      <div class="userselect"> </div>
      <div class="userselect"> </div>
      <div class="userselect"> </div>
      <div class="userselect"> </div>
      <div class="userselect"> </div>
    </div>

CSS

userselect{
        width:20px;
        height:20px;
        background:yellow;
        border:1px solid black;
        margin:5px;
    }
    .selected{
        background:green;
    }

JQuery

$(".userselect").on("click",function(oEvent){
   $(".userselect").removeClass("selected");
   $(this).addClass("selected");
    alert("you clicked : "+$(this).index());
});

Fiddle Demo

Upvotes: 0

Deepu Sasidharan
Deepu Sasidharan

Reputation: 5309

Are you looking for this one...

$("div").click(function(){
    $("div").css("background","none");
    $(this).css("background","green"); 
    var index = $(this).index();
    alert(index);
});

DEMO

Upvotes: 0

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

Try this DEMO

.green
{
    background-color:green;
    color:white;
}

JS

$('.parent div').on('click',function(){
    $('.parent div').removeClass('green');
    $(this).addClass('green');
});

$('#btncli').on('click',function(){
    alert($('.parent div.green').index());
});

Upvotes: 1

Styphon
Styphon

Reputation: 10447

You should apply a class to "select" a div, then apply styling to that class to make the background clean. Then you can just select the element by the class like this:

$('.my-class')

Upvotes: 0

monxas
monxas

Reputation: 2647

How are you changing the background color? if you are using $(".yourdiv").css("background-color","green") You should create a css class instead.

.selected{
     background-color: green;
}

And then add that class

$(".yourdiv").addClass("selected")

After that, you only need to call the selector like so:

$(".selected")

Upvotes: 1

Konstantin Dinev
Konstantin Dinev

Reputation: 34905

I assume the background color is applied with a class so:

$("div.green-color").index();

Upvotes: 0

Related Questions