Search code examples
jquerycssfindancestor

jQuery change css of given class within an id


$('#slider1 .rangeslider__handle').css("border", "4px solid #99cc44");

That syntax doesn't work for changing the border of only that class within the given id. I tried also

$.fn.hasAncestor = function(a) {
    return this.filter(function() {
        return !!$(this).closest(a).length;
    });
};
$('.rangeslider__handle').hasAncestor('#slider1').css("border", "4px solid #99cc44").change();

and

$('#slider1').find('.rangeslider__handle').css("border", "4px solid #99cc44");

Solution

  • You are using the plugin named "Range Slider".

    You certainly noticed that plugins creates new elements to achieve the nice visual effect, since your are after the element which has the .rangeslider__handle class.

    This element is div child of another div which has the .rangeslider class.
    And this one is the next sibling of the input type="range" from your initial HTML.

    So, to target the handle starting for your input id, you can use .next() then .find() as in the below snippet.

    I have placed the function on a button for clarity... and fun.

    $(document).ready(function(){
     var sliderValueShow = $("#showValue");
         
      $('#slider1').rangeslider({
        polyfill: false,
        onSlide: function(position, value) {
          sliderValueShow.html(value);
        },
        onSlideEnd: function(position, value) {
          sliderValueShow.html(value);
        }
      });
    
      // Change the handle border color
      $("#setColor").click(function(){
        $('#slider1').next().find('.rangeslider__handle').css("border", "4px solid #99cc44");
      });
    });
    #main{
      text-align:center;
      padding:20px;
    }
    #showValue{
      font-size:3em;
    }
    button{
      border-radius:10px;
      background-color:cyan;
      padding:6px;
      outline:none;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/rangeslider.js/2.3.0/rangeslider.js"></script>
    
    <link href="https://cdnjs.cloudflare.com/ajax/libs/rangeslider.js/2.3.0/rangeslider.css" rel="stylesheet"/>
    
    
    <div id="main">
      <input type="range" name="count" id="slider1" value="4" min="1" max="10"><br>
      <br>
      <span id="showValue">4</span><br>
      <br>
      <button id="setColor">Click me to change the handle border color</button>
    </div>