Reputation: 4212
I'm scraping a news website and I need to extract an element with multiple classes. My original code looks like this:
var index = $(this).attr('class');
And then append it as text to span:
$('.element').append('<span>.'+index+'</span>');
This works good for a single class, but when multiple classes are given it doesn't work(meaning I can't do my function). The reason for this is that the Jquery statement should have classes seperated by comma. So calling multiple classes will look like this in my code:
<span> .class1 class2 class3 </span>
But Jquery needs the comma's and dots like so:
<span> .class1, .class2, .class3 </span>
What can I do to add the comma's and dots?
Upvotes: 0
Views: 91
Reputation: 66981
Simply split the string by spaces into an array, then join it together again back into a string, and you'll be all set.
var index = $('div').attr('class').split(' ');
for (var i = 0; i < index.length; i++) {
index[i] = '.' + index[i];
}
index = index.join(', ');
Result would be .class1, .class2, .class3
Upvotes: 1