JQuery Selector by data attribute not working in Safari

The following warnings show one and two in FF, but only one in Safari. Is something in this line incompatible in Safari? if($('div[data-foo="'+bar+'"').hasClass('baz')){

JQuery

 alert('one'); if($('div[data-foo="'+bar+'"').hasClass('baz')){ alert('two'); }else{ alert('three'); } 

HTML

 <div data-foo="bar" class="baz"></div> 
+6
source share
2 answers

You do not have a closing bracket]. In addition, bar is a string literal in this case, not a variable. It works:

 alert('one'); if($('div[data-foo="bar"]').hasClass('baz')){ alert('two'); }else{ alert('three'); } 

Or you can define bar as a variable:

 var bar = "bar"; alert('one'); if($('div[data-foo="' + bar + '"]').hasClass('baz')){ alert('two'); }else{ alert('three'); } 

(I don't know how this works in Firefox before.)

+15
source

Depending on what you really want to do, where the warning instructions apply, you can make a shortcut with:

 $('div.baz').each(function(){ alert($(this).data('foo')); }); 

This should create a warning with the message bar

0
source

Source: https://habr.com/ru/post/956510/


All Articles