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/

2 Answers 2

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/

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

1 Comment

This works great, I just had to replace addClass(swatchColor) with `addClass(color) and worked a charm, Thanks!
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

3 Comments

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 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)
Great, thanks for the reply! I also found this aka $(this) -> stackoverflow.com/questions/3633270/…

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.