Home > Net >  Looping through a HTML list
Looping through a HTML list

Time:11-17

I would like to have a piece of JS which loops through a list-item series and for each list-item, it stores a unique attribute value (in this case, the href) and then inserts it as a data attribute to another element within the same list-item (in this case, the button). The JS which I have only applies the desired effect to the first list-item and not the whole series. Can my method be tweaked, or does it require surgery?

<li >
  <a  href="www.link_one.com">link one</a>
  <button >button one</button>
</li>
<li >
  <a  href="www.link_two.com">link two</a>
  <button >button two</button>
</li>
<li >
  <a  href="www.link_three.com">link three</a>
  <button >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);
});

CodePudding user response:

Inside forEach() you should use node.querySelector() instead of document.querySelector().

See https://jsfiddle.net/qkd37rsu/

CodePudding user response:

it's easier to follow if you work with your foreach node and from there get and set the attributes you want

  document.querySelectorAll('.productgrid--item').forEach(function(node) {
  var anchorHref = node.querySelector('.productitem--image-link').getAttribute('href');
  var addToCart = node.querySelector('.atc-button--text');
  addToCart.setAttribute('data', anchorHref);
  console.log(addToCart)
});
 
  
<li id='a' >
  <a id='a1'  href="www.link_one.com">link one</a>
  <button >button one</button>
</li>
<li id='b' >
  <a  href="www.link_two.com">link two</a>
  <button >button two</button>
</li>
<li id='c' >
  <a  href="www.link_three.com">link three</a>
  <button >button three</button>
</li>

  • Related