I fetch all css styles for an element by using this code:
JavaScript
x
2
1
style = window.getComputedStyle(dom, null)
2
so far so good.
I need to know if there styles and if, which class brings the CSS styles to this list.
For example we look the result line with
JavaScript
1
2
1
"background-image": "none",
2
I need to know if there is a class that applies this style and if there is a class which name has this class and in best case from which CSS file it is.
If there is a way to get this, info what is the best way to do that?
Advertisement
Answer
The below code is tested in my localhost. I have used jQuery.
HTML
JavaScript
1
71
71
1
<head>
2
<meta charset="UTF-8">
3
<meta name="viewport" content="width=device-width, initial-scale=1.0">
4
<meta http-equiv="X-UA-Compatible" content="ie=edge">
5
<link rel="stylesheet" href="style.css">
6
<link rel="stylesheet" href="style2.css">
7
<title>Document</title>
8
</head>
9
10
<body id="body">
11
12
13
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
14
<script>
15
jQuery(document).ready(function () {
16
captureLinks();
17
});
18
19
function captureLinks() {
20
hrefs = [];
21
jQuery("link").each(function () {
22
hrefs.push(jQuery(this).attr('href'));
23
})
24
css_styles = {};
25
hrefs_count = 0;
26
jQuery.each(hrefs, function (index, href) {
27
jQuery.ajax({
28
url: href,
29
success: function (data) {
30
css_styles[href] = data.replace(/ /g, '').replace(/(rnt|n|rt)/gm, "");
31
},
32
complete: function () {
33
hrefs_count = hrefs_count + 1;
34
if (hrefs_count === hrefs.length)
35
allCssCaptured(css_styles);
36
}
37
})
38
})
39
}
40
41
function allCssCaptured(css_styles) {
42
css_reference = "background-image:none";
43
css_reference_remove_white_space = css_reference.replace(/ /g, ':');
44
css_sheet_reference = {};
45
jQuery.each(css_styles, function (filename, content) {
46
if (content.indexOf(css_reference_remove_white_space) !== -1) {
47
split_content = content.split(css_reference_remove_white_space);
48
left_of_css_reference = split_content[0];
49
for (var i = left_of_css_reference.length; i >= 0; i--) {
50
if (left_of_css_reference[i] === '{') {
51
j = i - 1;
52
for (j = i - 1; j >= 0; j--) {
53
if (left_of_css_reference[j] === ".") {
54
css_string = '';
55
for (var k = j; k < i; k++) {
56
css_string += left_of_css_reference[k];
57
}
58
css_sheet_reference[filename] = css_string;
59
}
60
}
61
}
62
}
63
}
64
});
65
console.log(css_sheet_reference)
66
}
67
</script>
68
</body>
69
70
</html>
71
Stylesheet-2
JavaScript
1
5
1
.no-image {
2
color:yellow;
3
background-image: none;
4
}
5
Stylesheet
JavaScript
1
15
15
1
.b{
2
background-color: blue;
3
}
4
5
.a{
6
background-color: #000;
7
}
8
9
10
.test{
11
background-color: red;
12
width: 100px;
13
height: 50px;
14
}
15
And i got the console.log result of which stylesheet and which class.
Thank you.