I'm looking to iterate over every class defined on my html page once. I can get classnames back using Jquery, but I'm looking of way just to iterate over each individual classname once rather than for each time it appears on the page.
+1
A:
Kinda odd to do this, but here ya go
<html>
<head>
<title>Page</title>
<script src="jquery-1.3.2.min.js"></script>
<script>
$(function() {
var classes = {};
$("*[class]").each(function() {
var cs = $(this).attr("class").split(/\s/g);
for (var i = 0; i < cs.length; i++) {
if (!classes[cs[i]]) {
classes[cs[i]] = true;
}
}
});
for (var prop in classes)
alert(prop);
});
</script>
</head>
<body>
<div class="single"></div>
<div class="one two three"></div>
<div class="one two three"></div>
<div class="one two three four"></div>
<div class="one two three five"></div>
<div class="one two three six"></div>
</body>
</html>
Chad Grant
2009-05-04 10:29:23
er ... maybe I misunderstood the question .. lol
Chad Grant
2009-05-04 10:30:36
i was more meaning if you have class one defined 6 times on a page, selecting this and applying on operation based on the class (e.g. a border round element) but only doing this once as opposed to 6 times
AJM
2009-05-04 10:36:40
then no, that's just how jQuery works. It selects DOM objects based on your query and does things to them ... in your case 6 elements would have something changed .. 1 at a time. You want to look into changing your style rules at runtime which is completely different. You want something like this http://flesler.blogspot.com/2007/11/jqueryrule.html
Chad Grant
2009-05-04 10:49:05