How to Get Element's Attribute Set in CSS Class

How do you set a css class attribute with Javascript?

Use the style property to set the style in javascript.

LoadingImg.style.display = "block";

How to find all possible CSS Styles and Attributes of an Element?

You can check if the found elements are inside of other elements using jQuery $.contains()

More info here how to do this here: http://api.jquery.com/jQuery.contains/

So for your example to find if some found classes are inside set you can do:

$.each(foundElement, function(index, domElement){
if($.contains(domElement, $('.set'))) {
// domElement is inside the container with 'set' class
} else {
// domElement is not inside the container with 'set' class
}
});

How to get a style attribute from a CSS class by javascript/jQuery?

I wrote a small function that traverses the stylesheets on the document looking for the matched selector, then style.

There is one caveat, this will only work for style sheets defined with a style tag, or external sheets from the same domain.

If the sheet is known you can pass it in and save yourself from having to look in multiple sheets (faster and if you have colliding rules it's more exact).

I only tested on jsFiddle with some weak test cases, let me know if this works for you.

function getStyleRuleValue(style, selector, sheet) {
var sheets = typeof sheet !== 'undefined' ? [sheet] : document.styleSheets;
for (var i = 0, l = sheets.length; i < l; i++) {
var sheet = sheets[i];
if( !sheet.cssRules ) { continue; }
for (var j = 0, k = sheet.cssRules.length; j < k; j++) {
var rule = sheet.cssRules[j];
if (rule.selectorText && rule.selectorText.split(',').indexOf(selector) !== -1) {
return rule.style[style];
}
}
}
return null;
}

example usage:

var color = getStyleRuleValue('color', '.foo'); // searches all sheets for the first .foo rule and returns the set color style.

var color = getStyleRuleValue('color', '.foo', document.styleSheets[2]);

edit:

I neglected to take into consideration grouped rules. I changed the selector check to this:

if (rule.selectorText.split(',').indexOf(selector) !== -1) {

now it will check if any of the selectors in a grouped rules matches.

How do I target elements with an attribute that has any value in CSS?

The following will match any anchor tag with a rel attribute defined:

a[rel]
{
color: red;
}

http://www.w3.org/TR/CSS2/selector.html#pattern-matching


Update:
To account for the scenario @vsync mentioned, in the comment section (differentiating between emtpy/non-empty values), you could incorporate the CSS :not pseudo-class:

a[rel]:not([rel=""])
{
color: red;
}

https://developer.mozilla.org/en-US/docs/Web/CSS/:not

Javascript, CSS: Get element by style attribute

My suggestion is avoid doing this if at all remotely possible. Instead, use a class to assign the color value, and then you can look up the elements using the class, rather than the color value.

As far as I'm aware, there's no selector (not even in CSS3) that you can use to query a specific style value, which means looping through all elements (or it looks like you can restrict it to all elements with a style attribute) and looking at the element.style.color property. Now, the thing is, even though you write color: #333; in your style attribute, different browsers will echo it back to you in different ways. It might be #333, it might be #333333, it might be rgb(51, 51, 51), it might even be rgba(51, 51, 51, 0).

So on the whole, a very awkward exercise indeed.


Since you've said this is for a Chrome extension, you probably don't have to worry as much about multiple formats, although I'd throw in the ones that we've seen in the wild in case Chrome changes the format (perhaps to be consistent with some other browser, which has been known to happen).

But for instance:

(function() {

// Get all elements that have a style attribute
var elms = document.querySelectorAll("*[style]");

// Loop through them
Array.prototype.forEach.call(elms, function(elm) {
// Get the color value
var clr = elm.style.color || "";

// Remove all whitespace, make it all lower case
clr = clr.replace(/\s/g, "").toLowerCase();

// Switch on the possible values we know of
switch (clr) {
case "#333":
case "#333333":
case "rgb(51,51,51)": // <=== This is the one Chrome seems to use
case "rgba(51,51,51,0)":
elm.style.color = "#444";
break;
}
});
})();

Live example using red for clarity | source - Note that the example relies on ES5 features and querySelectorAll, but as this is Chrome, I know they're there.

Note that the above assumes inline style, because you talked about the style attribute. If you mean computed style, then there's nothing for it but to loop through all elements on the page calling getComputedStyle. Other than that, the above applies.

Final note: If you really meant a style attribute with precisely the value color: #333 and not the value color:#333 or color:#333333; or color: #333; font-weight: bold or any other string, your querySelectorAll could handle that: querySelectorAll('*[style="color: #333"]'). But it would be very fragile.


From your comment below, it sounds like you're having to go through every element. If so, I wouldn't use querySelectorAll at all, I'd use recursive descent:

function walk(elm) {
var node;

// ...handle this element's `style` or `getComputedStyle`...

// Handle child elements
for (node = elm.firstChild; node; node = node.nextSibling) {
if (node.nodeType === 1) { // 1 == Element
walk(node);
}
}
}

// Kick it off starting with the `body` element
walk(document.body);

That way you don't build up large, unnecessary temporary structures. This is probably the most efficient way to walk the entire DOM of a document.



Related Topics



Leave a reply



Submit