Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Browsers not observing changes to data-*, CSS attribute selector properties not rendering

Given this CSS:

[data-myplugin-object="blue-window"]{
    background-color: #00f;
}

[data-myplugin-object="red-window"]{
    background-color: #f00;
}

And this jQuery:

$('[data-myplugin-object="blue-window"]').each(function(event){
    $(this).data({
        'myplugin-object': 'red-window'
    });
});

And this HTML snippet:

<div data-myplugin-object="blue-window">
    <p>Hello world</p>
</div>

Now, one would expect that when the jQuery snippet is executed (properly deferred until page load is complete of course) my blue window (which does initially render as blue) would turn red.

Nope, it certainly does not; and using Firebug and Developer Tools in Firefox and Chrome respectively, I can't observe any changes to the data-* attributes.

In order for the browser (and DOM toolboxes for that matter) to observe changes, do I need to revert to .attr() or is there a workaround for this?

like image 600
Dan Lugg Avatar asked Sep 18 '11 00:09

Dan Lugg


People also ask

What are data -* attributes for?

The data-* attribute is used to store custom data private to the page or application. The data-* attribute gives us the ability to embed custom data attributes on all HTML elements.

What is CSS attribute selector?

The CSS Attribute Selector is used to select an element with some specific attribute or attribute value. It is an excellent way to style the HTML elements by grouping them based on some specific attributes and the attribute selector will select those elements with similar attributes.


1 Answers

jQuery.data() attributes are not actually stored on the DOM object in jQuery. The DOM object is tagged with a unique jQuery ID and the actual data is stored in a separate javascript data structure. Among other reasons, jQuery does it this way to prevent circular reference memory leak bugs that can happen in some browsers when data values are references to other DOM objects.

If you want to change the actual DOM attribute, I'd suggest setting the attribute directly yourself like this:

obj.attr("data-myplugin-object", "red-window");

Though, for what you're doing, I think most people would use adding/removing/changing CSS class names, not custom attributes as that is the common way of changing which CSS rules apply to an object.

<div id="myObj" class="blueWindow">
    <p>Hello world</p>
</div>

.blueWindow {background-color: #00F;}
.redWindow  {background-color: #F00;}

 $("#myObj").removeClass("blueWindow").addClass("redWindow");

Or if there are no other classes on the object:

 $("#myObj").attr("class", "redWindow");
like image 133
jfriend00 Avatar answered Sep 22 '22 15:09

jfriend00