Given an HTML document containing some CSS properties and the task is to get all the CSS styles of a particular element by using jQuery. The two approaches are as follows.
Approach 1: Use the document.defaultView.getComputedStyle() method to get all the cascading styles associated with that particular element. After that, append the style to a string one by one by traversing the object.
-
Example: The following example implements the above approach.
<!DOCTYPE HTML>
<
html
>
<
head
>
<
title
>
Getting all the CSS styles
of an element using jQuery
</
title
>
</
head
>
<
body
style
=
"text-align:center;"
>
<
h1
>GeeksForGeeks</
h1
>
<
p
id
=
"GFG_UP"
></
p
>
<
button
onclick
=
"GFG_Fun();"
>
Click Here
</
button
>
<
p
id
=
"GFG_DOWN"
></
p
>
<
script
>
var up = document.getElementById('GFG_UP');
var down = document.getElementById('GFG_DOWN');
up.innerHTML = "Click on the buttob "
+ "to get the all CSS styles "
+ "associated with the element.";
function GFG_Fun() {
var ar = document.defaultView
.getComputedStyle(up, null);
var str = "";
for (var key in ar) {
str = str + key + ': '
+ ar[key] + "-";
}
down.innerHTML = str;
}
</
script
>
</
body
>
</
html
>
chevron_rightfilter_none -
Output:
Approach 2: In this example, only specific styles are getting extracted. We can pass the name of the styles. In this approach, a method cssSpecific is defined that perform the string operations on the passed string and gets the properties from the object and returns them as a string.
-
Example: This example implements the above approach.
<!DOCTYPE HTML>
<
html
>
<
head
>
<
title
>
Getting all the CSS styles
of an element using jQuery
</
title
>
<
script
src
=
</
script
>
</
head
>
<
body
style
=
"text-align:center;"
>
<
h1
>GeeksForGeeks</
h1
>
<
p
id
=
"GFG_UP"
></
p
>
<
button
onclick
=
"GFG_Fun();"
>
Click Here
</
button
>
<
p
id
=
"GFG_DOWN"
></
p
>
<
script
>
var up = document.getElementById('GFG_UP');
var down = document.getElementById('GFG_DOWN');
up.innerHTML = "Click on the buttob to get"
+ " the all CSS styles associated "
+ "with the element.";
(function ($) {
$.fn.cssSpecific = function (str) {
var ob = {};
if (this.length) {
var css = str.split(', ');
var prms = [];
for (var i = 0, ii = css.length;
i <
ii
; i++) {
prms
=
css
[i].split(':');
ob[$.trim(prms[0])] = $(this)
.css($.trim(prms[1] || prms[0]));
}
}
return ob;
};
})(jQuery);
function GFG_Fun() {
var styles = $('#GFG_UP').cssSpecific(
'color, backgroundColor, opacity, height, lineHeight:height');
down.innerHTML
=
JSON
.stringify(styles);
}
</script>
</
body
>
</
html
>
chevron_rightfilter_none -
Output: