dozzzer
dozzzer

Reputation: 1

jQuery selector using data-value attribute with double quotes

I'm learning UI automated testing and I've been trying to locate this element

<a tabindex="-1" href="javascript:void(0)" data-value="{"stringVal":"date-desc-rank"}" id="s-result-sort-select_4" class="a-dropdown-link">Release Date</a>

on the web page using its "data-value" attribute.

But when I run the following:

$('a[data-value="{"stringVal":"date-desc-rank"}"]')

it returns an error:

Uncaught DOMException: Document.querySelector: 'a[data-value="{"stringVal":"date-desc-rank"}"]' is not a valid selector

I've also tried to escape double quotes with backslash symbols with no result.

Any help would be very much appreciated.

Upvotes: 0

Views: 1134

Answers (3)

dozzzer
dozzzer

Reputation: 1

Finally, the correct selector has been found:

$("a[data-value='{\"stringVal\":\"date-desc-rank\"}']")

Upvotes: 0

poorly-written-code
poorly-written-code

Reputation: 1073

I use encodeURIComponent to encode stuff when I want to store it in data-

And I have some prototypes on the String object to simplify the process.

String.prototype.encode = function() { return encodeURIComponent(this).replace(/'/g,'%27');};
String.prototype.decode = function() { return decodeURIComponent(this); };

`{"stringVal":"date-desc-rank"}`.encode(); //%7B%22stringVal%22%3A%22date-desc-rank%22%7D

<a data-value="%7B%22stringVal%22%3A%22date-desc-rank%22%7D">Release Date</a>

Side note for the other answer here, you can also use the attribute right in the selector, no need to filter.

$(`a[data-value="%7B%22stringVal%22%3A%22date-desc-rank%22%7D"]`).css('color', 'red');

Although you may want to consider using a simpler attribute for selectors, rather than an entire stringified object.

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

You need to use single quotes in the html to wrap the json and use escaped quotes in the jQuery selector.

Another approach is use $('a[data-value]').filter(function) and check the data in the callback. When a data attribute contains valid json, jQuery data() will automatically parse it to object/array for you.

// this version changes the text
$('a[data-value=\'{"stringVal":"date-desc-rank"}\']').text('Inserted text');

// this version changes the color
$('a[data-value]').filter(function(){  
   return $(this).data('value').stringVal === "date-desc-rank"
}).css('color', 'red');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a tabindex="-1" href="javascript:void(0)" data-value='{"stringVal":"date-desc-rank"}' id="s-result-sort-select_4" class="a-dropdown-link">Release Date</a>

Upvotes: 1

Related Questions