Sharavan
Sharavan

Reputation: 11

Trigger click of element with selected css value in jquery

i have some divs with same class please see this

<div class="parent" style="display:none">
        <div class="class-1" style="color:rgb(198, 172, 0);">hii</div>
        <div class="class-1" style="color:rgb(134, 122, 36);">hii</div>
        <div class="class-1" style="color:rgb(251, 206, 146);">hii</div>
        <div class="class-1" style="color:rgb(249, 70, 28);;">hii</div>
</div>

<div class="div2">text</div>

How to perform trigger click for class-1 which style colour is rgb(134, 122, 36)?

Upvotes: 0

Views: 214

Answers (3)

Kevin Kloet
Kevin Kloet

Reputation: 1086

you can use jQuery's trigger() with the help of the jQuery attribute equals selector

$(".class-1[style='color:rgb(198, 172, 0);']").on('click', function(){
	alert('works');
});

$(".class-1[style='color:rgb(198, 172, 0);']").trigger('click');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent" style="display:none">
        <div class="class-1" style="color:rgb(198, 172, 0);">hii</div>
        <div class="class-1" style="color:rgb(134, 122, 36);">hii</div>
        <div class="class-1" style="color:rgb(251, 206, 146);">hii</div>
        <div class="class-1" style="color:rgb(249, 70, 28);;">hii</div>
</div>

<div class="div2">text</div>

Upvotes: 2

pwnz22
pwnz22

Reputation: 469

You also can do something like this.

$(function(){
    $(".class-1[style='color:rgb(134, 122, 36);']").on('click', function(){
        alert('red');
    });

    $('.class-1').each(function (i, el) {
        if($(el).attr('style') == 'color:rgb(134, 122, 36);') {
        $(el).trigger('click')
      }
    })
})

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281646

You can loop over the elements with a given class and then compare their css color attribute and trigger a click if it matches your requirement.

$(document).ready(function(){
  $('.class-1').on('click', function(){
    alert($(this).css('color'));
  })
  $('.class-1').each(function(index, item) {
    console.log($(item).css('color') == 'rgb(134, 122, 36)');
    if($(item).css('color') == 'rgb(134, 122, 36)') {
      $(item).trigger("click");
    }
  })
  
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent" >
    <div class="class-1" style="color:rgb(198, 172, 0);">hii</div>
    <div class="class-1" style="color:rgb(134, 122, 36);">hii</div>
    <div class="class-1" style="color:rgb(251, 206, 146);">hii</div>
    <div class="class-1" style="color:rgb(249, 70, 28);;">hii</div>

</div>

<div class="div2">text</div>

Upvotes: 1

Related Questions