user2513846 user2513846 - 1 month ago 13
Javascript Question

How to check a class and then replace data-id for each element

I have my HTML tag like this:

<li class="myclass" data-target="#carousel-example-generic" data-slide-to="{dynamic.ID}"></li>


Its generated dynamically 1 to 5 times max.

How can I check each li class, and then change its element data-slide-to="" content attribute to a specific value? for example a different number.

for example on DOM ready the content is this:

<li class="myclass" data-target="#carousel-example-generic" data-slide-to="1"></li>

<li class="myclass" data-target="#carousel-example-generic" data-slide-to="2"></li>

<li class="myclass" data-target="#carousel-example-generic" data-slide-to="3"></li>


and rewrite it dynamically like this:

<li class="myclass" data-target="#carousel-example-generic" data-slide-to="0"></li>

<li class="myclass" data-target="#carousel-example-generic" data-slide-to="1"></li>

<li class="myclass" data-target="#carousel-example-generic" data-slide-to="2"></li>


vanilla Java Script is what I would like to do, but I guess i would be happy with jQuery as well.

Answer

Would something like this be helpful

var li = document.querySelectorAll('.myclass');

for (var i = 0; i < li.length; i++) {
  // for demo purpose, read existing value into the li's inner text
  li[i].textContent = 'old value: ' + li[i].getAttribute('data-slide-to');
  
  // change it
  li[i].setAttribute('data-slide-to', i);

  // for demo purpose, read it back into the li's inner text to show new value
  li[i].textContent += ' - new value: ' + li[i].getAttribute('data-slide-to');

}
<ul>
  <li class="myclass" data-target="#carousel-example-generic" data-slide-to="1"></li>

  <li class="myclass" data-target="#carousel-example-generic" data-slide-to="2"></li>

  <li class="myclass" data-target="#carousel-example-generic" data-slide-to="3"></li>
</ul>

Comments