niksos
niksos

Reputation: 433

jquery: set up child element color from data-attribute

Any idea how to make this work?

$("div[data-color]").each(function() {
    $(this).children('p').css('color', function () {
        return $(this).data('color')
    });
});

and the structure looks like

<div data-color="#ff0000"><p>text that needs right color</p></div>

Upvotes: 3

Views: 1372

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115222

No need of that callback function inside it this refers to p not the div.

$("div[data-color]").each(function() {
    $(this).children('p').css('color', $(this).data('color'))
});

$("div[data-color]").each(function() {
  $(this).children('p').css('color', $(this).data('color'))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-color="#ff0000">
  <p>text that needs right color</p>
</div>


Or do it with callback like

$("div[data-color] > p").css('color',function(){
    return $(this).parent().data('color');
    // or return this.parentNode.dataset.color
});

$("div[data-color] > p").css('color', function() {
  return $(this).parent().data('color');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-color="#ff0000">
  <p>text that needs right color</p>
</div>


With pure JavaScript use querySelectorAll and Array#forEach methods

Array.from(document.querySelectorAll("div[data-color] > p")).forEach(function(ele) {
  ele.style.color = ele.parentNode.dataset.color;
});

Array.from(document.querySelectorAll("div[data-color] > p")).forEach(function(ele) {
  ele.style.color = ele.parentNode.dataset.color;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-color="#ff0000">
  <p>text that needs right color</p>
</div>

Upvotes: 5

niksos
niksos

Reputation: 433

Yeah I realised it too. This works but yours too

$("div[data-color]").each(function() {
    $(this).find('p').css('color', $(this).attr('data-color'));
});

Upvotes: 1

Ram
Ram

Reputation: 144679

this in the css callback function refers the p element not the div element. You can use the second argument of the each callback.

$("div[data-color]").each(function(i, el) {
    $(this).children('p').css('color', function () {
        return $(el).data('color')
    });
});

Another option is:

$("div[data-color] > p").css('color', function () {
    return this.parentNode.getAttribute('data-color');
});

Upvotes: 2

Related Questions