lessismore lessismore - 10 months ago 53
Javascript Question

.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).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].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!

Answer Source

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].parentNode.setAttribute("data-name", tile_array[i]);

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