Home  >  Q&A  >  body text

Rewritten title: Looping over HTML lists

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);
});

P粉221046425P粉221046425427 days ago623

reply all(2)I'll reply

  • P粉302160436

    P粉3021604362023-09-10 15:11:24

    It will be easier to follow if you use a foreach node and get and set the required properties from there

      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' class="productgrid--item">
      <a id='a1' class="productitem--image-link" href="www.link_one.com">link one</a>
      <button class="atc-button--text">button one</button>
    </li>
    <li id='b' 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 id='c' 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>

    reply
    0
  • P粉270891688

    P粉2708916882023-09-10 14:01:02

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

    Please seehttps://jsfiddle.net/qkd37rsu/

    document.querySelector() selects and returns the first matching element in the entire document tree, while node.querySelector() only in node Searches a subtree of elements (and returns the first matching element). Note that node is just a parameter provided by forEach(function(node){...}).

    reply
    0
  • Cancelreply