简体   繁体   中英

Select Svg Path by fill color with jquery

I would like to not display all the white fill paths in my svg.

Imagine an svg with this structure:

<svg>
     <path class="pathok"fill="rgb(29,233, 182)"/>
     <path class="pathok" fill="rgb(255, 255, 255)" />
     <path class="pathok" fill="rgb(255, 255, 255)" />
     <path class="pathok" fill="rgb(255, 255, 255)"/> 
</svg>

I've tried with this but isn't working:

<script>
   if ($("path").attr("fill") == ("rgb(255, 255, 255)")) {
        $(this).css("display","none")
   }
</script>

Generally, How I could select tags by the value of his attribute?

Your selector is getting all of the paths, not an individual path.

Try this:

$(document).ready(function(){
    var $paths = $('path'); // Get all paths
    for (var i=0;i<$paths.length;i++){ // Iterate through each one
        var $path =$($paths[i]); // This gets a single path
        if ($path.attr("fill") == ("rgb(255, 255, 255)")) {
            $path.css("display","none");
        }
    }
});

You can just select the elements you want directly, no loops are required.

I've used rect elements rather than paths as you didn't supply and d attributes but the principle is the same.

 $("rect[fill='rgb(255, 255, 255)']").css('display', "none"); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <svg> <rect width="90" height="30" fill="black"/> <rect width="10" height="10" x="10" y="10" fill="rgb(29,233, 182)"/> <rect width="10" height="10" x="30" y="10" fill="rgb(255, 255, 255)" /> <rect width="10" height="10" x="50" y="10" fill="rgb(255, 255, 255)" /> <rect width="10" height="10" x="70" y="10" fill="rgb(255, 255, 255)"/> </svg> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM