The following show alert one and two in FF but just one in Safari. Is anything 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>
[attribute=”value”]: It selects the elements with a specified attribute and value. [attribute~=”value”]: It selects the elements with an attribute value which contains a specified word. [attribute|=”value”]: It selects the elements with the specified attribute which starts with the specified value.
To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API. $( "div" ).
The jQuery. hasData() method provides a way to determine if an element currently has any values that were set using jQuery. data() . If there is no data object associated with an element, the method returns false ; otherwise it returns true .
Which jQuery statement selects the DOM element with an id of testid'? Calling jQuery() (or $() ) with an id selector as its argument will return a jQuery object containing a collection of either zero or one DOM element.
You are missing a closing bracket ]. Also, bar is a string literal in this case, not a variable. This 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');
}
(Not sure how it was otherwise working in Firefox before.)
Depending upon what you want to really do where the alert statements are, you could make a shortcut with:
$('div.baz').each(function(){
alert($(this).data('foo'));
});
This should create an alert stating bar
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With