I have a list of elements with Custom Data Attributes. I need to be able to add a class to another element on click when the data attribute of a clicked element matches the data attribute of that element.
HTML
<div data-my-element="value1">click 1</div>
<div data-my-element="another">click 2</div>
<div data-my-element="oneMore">click 3</div>
<section data-my-element="value1"></section>
<section data-my-element="another"></section>
<section data-my-element="oneMore"></section>
JS
$('div').click(function() {
var myEm = $(this).val('data-my-element');
$('section[data-my-element = '+myEm+']').addClass('clicked');
});
I think I'm doing something wrong.
FIDDLE
Try this:
$('div').click(function() {
var myEm = $(this).attr('data-my-element');
//alert(myEm);
$('section[data-my-element = '+myEm+']').addClass('clicked');
});
You are also missing:
);
after }
at the end of your code
JSFiddle Demo
Change:
var myEm = $(this).val('data-my-element');
To:
var myEm = $(this).data('my-element');
And if any of the data is being inserted or changed dynamically, you may consider using:
$('section').filter(function() {
return $(this).data('my-element') == myEm;
}).addClass('clicked');
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