1

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/

user27068
  • 179
  • 2
  • 10

2 Answers2

3

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/

Tamil Selvan C
  • 19,913
  • 12
  • 49
  • 70
  • 1
    This works great, I just had to replace `addClass(swatchColor)` with `addClass(color) and worked a charm, Thanks! – user27068 Mar 15 '15 at 02:39
2

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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • I see this is a more elegant solution, but takes me a minute to follow. How would you describe the difference between the 2 solutions? i.e. describe the difference between using `$(this).parent)()` vs `this.parentNode` – user27068 Mar 15 '15 at 02:48
  • @user27068 one uses the jQuery method(`$(this).parent)()`) where as the other one uses vanila script(`this.parentNode`) only, so the vanila script based solution will work only on modern browsers(won't work in IE<=8) – Arun P Johny Mar 15 '15 at 02:53
  • Great, thanks for the reply! I also found this aka $(this) -> http://stackoverflow.com/questions/3633270/difference-between-this-and-this-in-jquery – user27068 Mar 15 '15 at 03:05