Anthony Anthony - 27 days ago 15
HTML Question

Can you add a class to multiple elements in a single line of code?

My current code requires 3 lines of code to give these charts their animation. is there a way to define multiple elements in one line of code, something like this? I'm trying to clean up my code and make it easier for others to understand and the less clutter the better.

$('#container1,container2,container3').addClass('animated zoomInDown');




$(document).ready(function() {
Highcharts.chart('container1', {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false,
type: 'pie'
},
title: {
text: 'What grade are you in?'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {point.percentage:.1f} %',
style: {
color: (Highcharts.theme && Highcharts.theme.contrastTextColor) || 'black'
}
}
}
},
series: [{
name: 'Percentage',
colorByPoint: true,
data: [{
name: '9th',
y: 0
}, {
name: '10th',
y: 16.7,
sliced: true,
selected: true
}, {
name: '11th',
y: 25
}, {
name: '12th',
y: 58.3
}]
}]
});
});

<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css" rel="stylesheet" />
<div id="container1" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
<script>
$('#container1').addClass('animated zoomInDown');
</script>
<div id="container2" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
<script>
$('#container2').addClass('animated zoomInDown');
</script>
<div id="container3" style="min-width: 310px; height: 400px; max-width: 600px; margin: 0 auto"></div>
<script>
$('#container3').addClass('animated zoomInDown');
</script>




Answer

For selecting multiple elements with an id that has a common prefix try this:

$('[id^=container]')

and then you use the addClass method.