user27068
user27068

Reputation: 179

Write HTML in reference to attribute data with Javascript

I would like to add a class to an adjacent element using the attribute of an anchor tag with javascript:

HTML:

<ul>
    <li><a href="#" class="swatchButton" data-color="blk"><span></span>Black</a></li>
    <li><a href="#" class="swatchButton" data-color="red"><span></span>Red</a></li>
    <li><a href="#" class="swatchButton" data-color="blu"><span></span>Blue</a></li>
    <li><a href="#" class="swatchButton" data-color="grn"><span></span>Green</a></li>
    <li><a href="#" class="swatchButton" data-color="yel"><span></span>Yellow</a></li>
</ul>      

JS:

$(document).ready(function(){
    var swatchColor = $(".swatchButton").data('color');
    $(".swatchButton").find('span').addClass(swatchColor);
});

I'm eventually looking for:

<li><a href="#" class="swatchButton" data-color="blk"><span class="blk"></span>Black</a></li>

Do I need to create some kind of array with forEach()?

Thanks! http://jsfiddle.net/cL1rpk9L/

Upvotes: 1

Views: 43

Answers (2)

Tamil Selvan C
Tamil Selvan C

Reputation: 20209

use each() in jquery

$(document).ready(function(){
    $(".swatchButton").each(function() {
        var swatchColor = $(this).data('color');
        $(this).find('span').addClass(swatchColor);
    });

});

Demo: https://jsfiddle.net/tamilcselvan/cL1rpk9L/3/

Upvotes: 3

Arun P Johny
Arun P Johny

Reputation: 388316

Your code var swatchColor = $(".swatchButton").data('color'); will return the data-color of the first element with class swatchButton and $(".swatchButton").find('span').addClass(swatchColor); will assign that value to each span element which is a descendant of an element with class swatchButton.

You need to set the color for each span individually

$('.swatchButton span').addClass(function(){
    return this.parentNode.dataset.color;
});

Demo: Fiddle

or

$('.swatchButton span').addClass(function(){
    return $(this).parent().data('color');
});

Demo: Fiddle

Upvotes: 2

Related Questions