I want a JS code that loops through a series of list items, and for each list item it stores a unique attribute value (in this case, the href) and then inserts it inside the same list item within another element (in this case, the button). My current JS code only works on the first list item, not the entire series. Can my approach be tweaked, or does it need to be modified?
<li class="productgrid--item"> <a class="productitem--image-link" href="www.link_one.com">link one</a> <button class="atc-button--text">button one</button> </li> <li class="productgrid--item"> <a class="productitem--image-link" href="www.link_two.com">link two</a> <button class="atc-button--text">button two</button> </li> <li class="productgrid--item"> <a class="productitem--image-link" href="www.link_three.com">link three</a> <button class="atc-button--text">button three</button> </li>
document.querySelectorAll('.productgrid--item').forEach(function(node) { var anchorHref = document.querySelector('.productitem--image-link').getAttribute('href'); var addToCart = document.querySelector('.atc-button--text'); addToCart.setAttribute('data', anchorHref); });
It will be easier to follow if you use a foreach node and get and set the required properties from there
In
forEach()
, you should usenode.querySelector()
instead ofdocument.querySelector()
.Please seehttps://jsfiddle.net/qkd37rsu/
document.querySelector()
selects and returns the first matching element in the entire document tree, whilenode.querySelector()
only innode
Searches a subtree of elements (and returns the first matching element). Note thatnode
is just a parameter provided byforEach(function(node){...})
.