0

Is there a way to add a "dynamic" data-attribute to a DOM element with jQuery?

This, for example, doesn't work:

var value = 100;

// hoping to add a 'data-100' attribute 
$('div').attr({
  String('data-' + value) :'display: block'
});

It throws the error:

Uncaught SyntaxError: Unexpected token (

obs: as far as I know if you sum a string with an integer in JS, it will cast everthing as a String, but anyway I tried with String() because maybe in some language that worked for me once.

This obviously won't work (it will add the 'custom_data' and not the 'data-100' attribute):

var custom_data = 'data-100';

// hoping to add a 'data-100' attribute 
$('div').attr({
  custom_data :'display: block'
});
2
  • Javascript doesn't have type coercion, what makes you think String() would be valid ? Commented Feb 27, 2015 at 19:28
  • 1
    $('div').attr('data-'+value, 'display: block'); Commented Feb 27, 2015 at 19:29

1 Answer 1

2

Do

$('div').attr("data-"+value,"display:block");

Your syntax is wrong see similar

Fiddle

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

1 Comment

Got it, it shouldn't be inside an object. Though it works that way, except that it tries to cast the key to a string, is that correct?

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.