简体   繁体   中英

Iterate through a list of elements and check for existence of custom data attribute containing a value

My pseudocode looks like this:

for (class='delivery') {
  if (i[date ~= 'Tomorrow']) {
    i.append(<div>50p</div>)
  }
  else {
    i.append(<div>FREE</div>)
  }
}

So in other words, I want to generate a list (array or object, whatever works) of nodes with a certain class name, and as I iterate through them I want to say 'if the custom data attribute of 'date' (that they all have) contains 'Tomorrow' I append a div containing '50p', or else I append a div containing 'FREE'. I can do this with JS or Jquery.

With vanilla JS:

 document.querySelectorAll('.delivery').forEach((e) => { var date = e.getAttribute('data-date'); if (date != null && date.includes('Tomorrow')) { e.innerHTML+='<div>50p</div>'; } else { e.innerHTML+='<div>FREE</div>'; } })
 <div class="delivery" data-date="Tomorrow"></div> <div class="delivery" data-date="Today"></div> <div class="delivery" data-date="Yesterday"></div>

With jQuery:

 $('.delivery').each(function() { var date = $(this).attr('data-date'); if (date != null && date.includes('Tomorrow')) { $(this).append('<div>50p</div>'); } else { $(this).append('<div>FREE</div>'); } })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="delivery" data-date="Tomorrow"></div> <div class="delivery" data-date="Today"></div> <div class="delivery" data-date="Yesterday"></div>

Ignore css , it's just for representational purpose only.

 const elements = [...document.querySelectorAll(".delivery")]; const result = elements.forEach(el => { const doesDataAttrExist = el.dataset.date && el.dataset.date.includes("Tomorrow"); const element = document.createElement("div"); if (doesDataAttrExist) { element.textContent = "50p"; el.appendChild(element); } else { element.textContent = "free"; el.appendChild(element); } })
 div.delivery { background: lightgray; padding: .5rem; border-radius: 4px; margin: .25rem; display: flex; justify-content: space-between; } div[data-date] { background: teal; color: white; }
 <div class="delivery" data-date="Tomorrow">1</div> <div class="delivery">2</div> <div class="delivery" data-date="Tomorrow">3</div> <div class="delivery">4</div> <div class="delivery">5</div> <div class="delivery" data-date="Tomorrow">6</div> <div class="delivery">7</div> <div class="delivery">8</div> <div class="delivery" data-date="Tomorrow">9</div> <div class="delivery">10</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM