Pull element that has a specific attribute with javascript

-1

I have a page with four Divs, all with the class .coloritem:

<div class="coloritemSelected" style="background: Vermelho;" onclick="javascript:showOptionsFor('Vermelho');">&nbsp;</div>
<div class="coloritem" style="background: red;" onclick="javascript:showOptionsFor('Azul');">&nbsp;</div>
<div class="coloritem" style="background: red;" onclick="javascript:showOptionsFor('Púrpura');">&nbsp;</div>
<div class="coloritem" style="background: red;" onclick="javascript:showOptionsFor('Laranja');">&nbsp;</div>

I would like to know if you have just how to get the div that has such a color, like Red and change it so that it has background: red;

I was testing with this code, but it ends up putting the color in all the Divs:

$(document).ready(function () {
    var item = $('.coloritem');
    var background = item.attr('style');
    if (background == 'background:Vermelho;') {
        $(item).css('background', 'red');
    };
});

Thanks in advance for any help.

    
asked by anonymous 11.12.2017 / 17:34

2 answers

1

Come on. To understand why all divs are being affected, just understand this line of your code:

var item = $('.coloritem');

If you give console.log(item); you will notice an Array of items, because this selector has retrieved all items that have class .coloritem .

To solve this, you will need to use something that filters out exactly the element you want. Fortunately jQuery has exactly the filter(); This method receives a string that will be used as selector, hence the return of it will be only the objects that have such selector within an existing selector .. That is:

var item = $('.coloritem');
var t = item.filter('style["background: Vermelho;"]'); // aqui terá apenas o item cujo style seja background Vermelho

Now you can change the color of the object t normally.

I hope I have helped.

(See Paulo Imon's comment.)

    
11.12.2017 / 18:00
0

11.12.2017 / 19:15