CSS not responding to data-attribute set via jQuery
Asked Answered
S

3

8

I am setting a data-position attribute on document ready via jQuery on several divs. The setting definitely works. For example, calling the below code in the Chrome console is returning 'left'.

$('.card-container').data('position');

However in the CSS the below is not doing anything.

[data-position='left']

Hard-coding data-position="left" in the div is working though. What am I doing wrong? Thanks for the help

Sense answered 15/10, 2013 at 10:39 Comment(2)
Using data doesn't actually add the data attribute to the markup, so it won't affect css. You should add a class instead.Cutler
$('.card-container').attr('data-position',"set your value");Decalcomania
G
16

Setting a data attribute as you are means that it is stored in jQuery's cache (which is an object in memory), it does not get set as an attribute on the element and therefore no CSS selector will see it.

You would need to manually set the data attribute using attr for this to work:

$('.card-container').attr('data-position', 'left');

Note however, that this will see slightly reduced performance when retrieving the data value, although we're talking miliseconds.

Guimond answered 15/10, 2013 at 10:45 Comment(0)
D
2
$('.card-container').attr('data-position',"set your value");

reference attr

Decalcomania answered 15/10, 2013 at 10:42 Comment(0)
T
0

jQuery's data() method doesn't actually change the attribute. In order to change the attribute on the element itself you'll have to use attr():

$('.card-container').attr('data-position', 'value');
Toast answered 15/10, 2013 at 10:42 Comment(2)
This does NOT change the 'data-position' attribute, but adds another attribute called 'position'Ingridingrim
@Ingridingrim that's a good point! I'm clearly too tired to answer questions accurately today...Toast

© 2022 - 2024 — McMap. All rights reserved.