I am trying to write a piece of code that when a button is clicked, it checks through a list of images, checks if it has an id of ‘video’ and if it does then display an overlay and remove the player that is there.
I keep getting this error:
Uncaught TypeError: Cannot call method 'indexOf' of undefined
Here is the code:
$("#actions .btn").click(function(){
$('.span img').each(function(){
if($(this).attr('id').indexOf('video') != -1){
var spanid = $(this).attr('id').replace(/video/, '');
$(this).removeClass('hideicon');
$('#mediaplayer' + spanid + '_wrapper').remove();
}
});
});
The
.attr()method will returnundefinedif the attribute you’re looking for doesn’t exist on the element. I would suggest adding an extra check to your condition:From the docs:
Interestingly, the native
getAttributefunction returnsnullfor attributes that haven’t been set. jQuery, for some reason, explicity checks for this and returnsundefinedinstead: