lessismore
lessismore

Reputation: 177

.each() add an attribute to a parent from jquery to js

I am a newbie in js and jquery and need help with rewriting my code from jquery to pure js.

I've got several parent divs. Each of them have a child div inside.

I want to add a class to both child and parent, but to parent as an attribute value in data-name.

Class names are stored in an array, in other words first parent and its child will get a array[0] class name, second parent and its child - array[1] class name, etc.

I use this jquery for this

$(".back").each(function(i) {
    $(this).addClass(tile_array[i]);
    $(this).parent().attr("data-name", tile_array[i]);
});

I tried to rewrite it in js like this:

var backs = document.querySelectorAll('back');
for (let i = 0; i < backs.length; i++) {
    for (let j = 0; j < tile_array.length; j++) {
        backs[i].classList.add(tile_array[j]);
        backs[i].parentNode.setAttribute("data-name", tile_array[j]);
    }
}

However, this does not work. How should I rewrite my code so that it works properly?

Thanks in advance!

Upvotes: 6

Views: 77

Answers (2)

wscourge
wscourge

Reputation: 11281

You can skip the inner loop - you don't use it in your jQuery, why would you do that here?

Also, to set data attribute there is .dataset element property in Javascript. So your final code would be like:

var backs = document.querySelectorAll('back');
for (let i = 0; i < backs.length; i++) {
  backs[i].classList.add(tile_array[i]);
  backs[i].parentNode.dataset.name = tile_array[i]
}

Upvotes: 0

user6752436
user6752436

Reputation:

try this : backs.length and tile_array.length are same .so no need ah inner loop

for (let i = 0; i < backs.length; i++) {
        backs[i].classList.add(tile_array[i]);
        backs[i].parentNode.setAttribute("data-name", tile_array[i]);
   }

And add a class in querySelectorAll('.back')

Upvotes: 4

Related Questions