Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Selector by data attribute not working in Safari

Tags:

jquery

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>
like image 200
Joseph Avatar asked Oct 22 '13 21:10

Joseph


People also ask

How do I select an element with a data attribute?

[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.

How get data attribute value in jQuery?

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" ).

How do you check if data attribute exists in jQuery?

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?

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.


2 Answers

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.)

like image 199
mayabelle Avatar answered Oct 14 '22 06:10

mayabelle


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

like image 34
Sablefoste Avatar answered Oct 14 '22 04:10

Sablefoste