2

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'));
}
2
  • <div>s don't have values. .val() is for form elements. Commented May 13, 2013 at 20:45
  • Oh yes, sorry about that, I've updated the question. Commented May 13, 2013 at 20:47

3 Answers 3

2

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/

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

Comments

0

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+.

Comments

0

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

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.