Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding class to element with matching custom data attribute

Tags:

jquery

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

like image 366
santa Avatar asked Jul 28 '14 17:07

santa


2 Answers

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

like image 129
imbondbaby Avatar answered Oct 13 '22 23:10

imbondbaby


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');
like image 31
PeterKA Avatar answered Oct 13 '22 23:10

PeterKA