Here's a simple question: using jQuery's css
function, you can retrieve the computed style of a CSS attribute. But what if there are multiple styles for that attribute being rendered simultaneously? Let's consider this example:
<div id="foo" style="text-decoration:underline;">Some underline text</div>
Executing
$('#foo').css('text-decoration');
will return underline
. Now, let's complicate things a bit by adding another element:
<div id="foo" style="text-decoration:underline;">Some underline <span id="bar" style="text-decoration:line-through;">text</span></div>
Running
$('#bar').css('text-decoration');
will give us line-through
, but the actual text is still underline
! How do we get both values? Do we have to search through all ancestors to find out if some text has both underline
and line-through
? Sounds like a tedious task, doesn't it?
** Edit **
Yet another issue arises with this HTML snippet:
<span style="text-decoration:underline;">some <span id="e1" style="font-weight:bold;">text</span></span>
Oddly enough, $('#e1').css('text-decoration');
returns none
even though the text clearly has an underline. Strange, isn't it?
** Disclaimer **
Let's not delve into how the User Agent renders an element, but rather focus on whether an element hierarchy applies a CSS or not. For those seeking more clarity on text-decoration
, I recommend reading about it here. This question aims to address a broader scope. For instance, it can also be applied to the following HTML:
<div style="display:none;">Some <span id="keyword" style="text-decoration:underline;">hidden</span> text</div>
In this scenario, one might want to determine if the element keyword
is visible or not. With the code below, you can easily check:
cssLookup($('#keyword'), 'display', 'none'); // -> true
** UPDATE **
After considering all the answers and comments, here is a solution inspired by Brock Adams' response :
/**
* Lookup the given node and its parents for a specific style value. Returns boolean
*
* @param e element (jQuery object)
* @param style the style name
* @param value the value to look for
* @return boolean
*/
function cssLookup(e, style, value) {
var result = (e.css(style) == value);
if (!result) {
e.parents().each(function() {
if ($(this).css(style) == value) {
result = true;
return false;
}
});
}
return result;
}
Big thanks to everyone for sharing your insights.