nlips
nlips

Reputation: 1288

Selector based on css property

Is it possible to select elements based on the value of a CSS property. For example:

CSS rules:

div.blockWithBorder { border: 1px solid red; }

HTML markup:

<div id="A" class="blockWithRedBorder">...</div>
<div id="B" style="border: 5px dashed red">...</div>
<div id="C" style="border: 2px solid #FF0000">...</div>

I want to find all div elements with a red border. A, B and C match this query.

Upvotes: 0

Views: 397

Answers (3)

A. Wolff
A. Wolff

Reputation: 74420

You can filter set of elements:

var $divsBorderRed = $('div').filter(function(){
    return ~this.style.borderColor.indexOf("red") || ~this.style.borderColor.indexOf("rgb(255, 0, 0)") || ~this.style.borderColor.indexOf("#FF0000")
});

EDIT: or like this:

var $divsBorderRed = $('div.blockWithRedBorder, div[style*="#FF000"], div[style*="red"]');

As you can see, that's not great in all cases...

Upvotes: 1

Yasser Shaikh
Yasser Shaikh

Reputation: 47784

Firstly, you SHOULD NOT have to code for this. A class like "blockWithRedBorder" or some selector should be present. Saying that incase you are looking for a quick fix below is something that should help you....

You could iterate through all the divs and read the border css property like this : jsfiddle

$("div").each(function(i, item){
    var selector = '#' + item.id;
    var yourValue = $(selector).css("border");
    // you can perform your 'red' color check here
    // make sure to match it with 'rgb(255, 0, 0)' and with color 'red'.
});

Upvotes: 0

Jack
Jack

Reputation: 9538

You could do this, but it would mean getting the computed style value for each element you were querying against which could be a very expensive operation.

Here's an example:

var a = [].slice.call(document.querySelectorAll("a"));

var redLinks = a.filter(function(i){
  window.getComputedStyle(i);
  var color = i.style.borderColor.toLowerCase();
  return (color === 'red' || color === '#f00' || color === '#ff0000') ? i : false;
});

Upvotes: 2

Related Questions