You can use the has attribute selector ([]
) to test for an attribute presence:
$('li[data-option]').each(function () {
var dataOption = $(this).attr('data-option');
$(this).find('ul').addClass(dataOption);
});
Check demo here.
Note: You could use .data('option')
instead of .attr('data-option')
. It is a matter of choice, really. In this case I used .attr()
because .data()
is more of a "storage" than an attribute accessor function - and, as you are plainly accessing the data-option
attribute, with no conversion from the string value, the .attr()
function seems to denote your intention in the code better.