Reputation: 3802
How to get previous all element class list using jquery.
Here is the Example.
<div>
<div>
<span class="one">one</span>
</div>
<div>
<span class="two">one</span>
</div>
<div>
<span class="three">one</span>
</div>
<div id="getclass">getclass</div>
<div>
<span class="four">one</span>
</div>
</div>
I want all the class names above in "getclass" id.
And i'm trying the below things.
var a = $("#getclass").prevAll().find('.class').attr('class');
How can i achive this using jquery.Anyone please Help me to fix this issue.
Upvotes: 2
Views: 133
Reputation: 829
You can read each element through a loop:
<script type="text/javascript">
$(function () {
var classes = [];
$("#getclass").prevAll().each(function () {
classes.push($(this).find('span').attr('class'));
});
var classNames = classes.join(",");
alert(classNames);
});
classes is an array of class names, you can also get it as a CSV.
Upvotes: 1
Reputation: 5967
Your code is looking for elements with the class class.
You can instead get all children of previous siblings and then use the map
function to convert this to an array with just class names by returning the className
property.
Example:
var a = $("#getclass")
.prevAll()
.children("span")
.get()
.map(function(x) {
return x.className;
});
console.log(a);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
<span class="one">one</span>
</div>
<div>
<span class="two">one</span>
</div>
<div>
<span class="three">one</span>
</div>
<div id="getclass">getclass</div>
<div>
<span class="four">one</span>
</div>
</div>
Upvotes: 4