6

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

3
  • 1
    Don't use $(this).val('data-my-element') instead use $(this).data("my-element");. jQuery Data(). Commented Jul 28, 2014 at 17:18
  • 2
    You can use the data() method to get the value of the data attribute (or the attr method). Your call to val() is actually setting the value (even though val() would not work because that is used for input, select, and textarea) Commented Jul 28, 2014 at 17:19
  • You're also missing a few things in your script: addClass('clicked'); and }); Commented Jul 28, 2014 at 17:22

3 Answers 3

21

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

Sign up to request clarification or add additional context in comments.

1 Comment

This helped me a lot after hours of struggling!!
4

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');

Comments

0

Change -

var myEm = $(this).val('data-my-element'); //doesn't have a value

to this -

var myEm = $(this).attr('data-my-element'); // returns the value of the custom attribute

or this

var myEm = $(this).data('my-element');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.