I've created a Custom Admin page on wordpress back-end, and have this basic html structure,
<ul data-status="available">
<li class="available">AVAILABLE</li>
<li class="onleave">ONLEAVE</li>
</ul>
When I use js code below, it works fine
$('ul').each( function() {
var status = 'available';
$(this).find('li.' + status ).addClass('active');
});
While this code below also works (it adds class on element), However it, produces an error
$('ul').each( function() {
var status = $(this).data('status');
$(this).find('li.' + status ).addClass('active');
});
Error on Console
Syntax error, unrecognized expression: li. load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=4.4.1:2
(9 Errors) Cannot read property 'hasClass' of undefined load-scripts.php?c=0&load[]=hoverIntent,common,admin-bar,svg-painter,heartbeat,wp-auth-check,thickb…:246
Any clear explanation would be highly appreciated
FULL JS CODE
( function($) {
'use strict';
$(document).ready( function() {
$('ul').each( function() {
var status = $(this).attr('name');
//$(this).find('li.' + status ).addClass('active');
});
$('form').on('click', 'li', function() {
var currentStatus = $(this).parent().attr('name');
var id = $(this).parent().attr('id');
var status = $(this).attr('name');
var input = '<input id="model-'+id+'" type="hidden" name="'+id+'" value="'+status+'" />'
if( currentStatus !== status || !currentStatus ) {
$('form').prepend( input );
} else {
$('form').find('#model-'+id).remove();
}
$(this).parent().find('li').removeClass('active');
$(this).addClass('active');
});
$('form').submit( function(e) {
e.preventDefault();
console.log( $( this ).serialize() );
});
});
})(jQuery);
uls you are looping through (maybe one not created by you) has an undefineddata-status. Generally I think it is not the best practice to use html elements in.each()or.on(). It would be much better (and safer) to explicitly attach the handlers to specific elements through classes or ids.has an undefined data-status-- thanks, this line gave me an idea, it could be that some UL doesn't havedata-statusvalue. I'll check the source code. since all these datas are pulled from databaseif (typeof status === 'undefined' || !status) { return; }than it should also work.