user2352358
user2352358

Reputation: 77

jQuery Change Value Using Data Attribute

I have multiple elements that'll have the same data attributes but with different values, how can I get jQuery to change the value?

Below is some example HTML.

<div data-one="test" data-two="test2"></div>
<div data-one="testing" data-two="hello"></div>
<div data-one="yo" data-two="test3"></div>

By default, I would like to the value of div to be data-one but then when the class active is on the body tag, I would like it to change all the values to the data-two value.

I thought about storing values as a variable which would be easier although the divs don't have any ID's and they're scattered around in the DOM which makes it difficult.

So far I had this:

if($('body').hasClass('active')) {
  $('div').html($(div).data('two'));
}

Upvotes: 2

Views: 149

Answers (3)

user1
user1

Reputation: 1065

Check this link: http://jsfiddle.net/rjR6q/

$(document).ready(function(){
if($('body').hasClass('active')) {
$('div').each(function(){
    $(this).html($(this).data('two'));
});
}
 else
{
$('div').each(function(){
    $(this).html($(this).data('one'));
});
}
});

Upvotes: 0

dfsq
dfsq

Reputation: 193261

CSS only solution:

body div:after {
    content: attr(data-one);
}
body.active div:after {
    content: attr(data-two);
}

http://jsfiddle.net/dfsq/gaeUR/

However it's not crossbrowser: attr function is supporter in IE8+.

Upvotes: 0

Ram
Ram

Reputation: 144659

You can use html method.

var has = $('body').hasClass('active');
$('div').html(function() {
    return has ? $(this).data('two') : $(this).data('one');
});

http://jsfiddle.net/44Du5/

Upvotes: 2

Related Questions