Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search by data attribute, and replace

Tags:

html

jquery

This is my HTML

<a href="#" data-finder-code="" data-dropdown-placeholder="Select..." data-dropdown-text="1">Samsung</a>

And this is my JQuery

var finder_code = 39;
$("a[data-dropdown-text='1']").data("finder-code", finder_code);

When i search by $("a[data-dropdown-text='1']") and try to replace the data-finder-code in the same href nothing happens. How do i get this to work?

like image 537
user2636556 Avatar asked Apr 18 '26 04:04

user2636556


2 Answers

Your code is working fine. When you use data() jQuery only updates its internal cache for performance reasons. If you retrieve the value using the getter of data(), then you can see it's working fine:

var finder_code = 39;
$("a[data-dropdown-text='1']").data("finder-code", finder_code);

console.log($("a[data-dropdown-text='1']").data('finder-code'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" data-finder-code="" data-dropdown-placeholder="Select..." data-dropdown-text="1">Samsung</a>

If you have to update the value in the DOM, then you can use attr('data-finder-code'), however it will be marginally slower:

var finder_code = 39;
$("a[data-dropdown-text='1']").attr('data-finder-code', finder_code);
like image 130
Rory McCrossan Avatar answered Apr 19 '26 23:04

Rory McCrossan


jQuery uses internal cache to persist arbitrary data when using .data(key, value) it won't update the DOM.

Otherwise your code will work. However If you want to update the attribute value use .attr(key, value)

$("a[data-dropdown-text='1']").attr("data-finder-code", finder_code);
like image 41
Satpal Avatar answered Apr 20 '26 01:04

Satpal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!