Search code examples
jqueryhtmlhtml-manipulation

Change div content dynamically with jQuery


I'm wondering how I can change the html content of a div.

This is the starting point:

<div id="container">
    <div class="fruits">apple</div>
    <div class="fruits">banana</div>
    <div class="fruits">strawberry</div>
</div>

Output on page:

apple
banana
strawberry

The output should be changed to:

cat
dog
fish
...or something like this.

I guess I have to iterate over the class "fruits" with .each() or something. I know how to change single elements or content of a single div, but i don't understand how that works when you have the same class for multiple times.

class="fruits"
class="fruits"
class="fruits"
....

Hope you can help.


Solution

  • JavaScript

    const items = ["cat", "dog", "fish"];
    
    document.querySelectorAll(".item").forEach((el, i) => {
      el.textContent = items[i];
    });
    <div id="container">
      <div class="item">apple</div>
      <div class="item">banana</div>
      <div class="item">strawberry</div>
    </div>

    jQuery

    var animals = ["cat", "dog", "fish"];
    
    $(".fruits").text(function(i){
      return animals[i];
    });
    

    Store your animals into an Array,
    Loop with the .text() callback over your .fruits selector, and modify the text by returning the index of the animals that matches the current index i (animals[i]).

    In case you have more selectors elements than the Array length you can modulo the result using: return animals[i%animals.length];

    jsBin demo


    Since it's not clear where you're storing your Animals strings,
    you can use also this simple example to achieve what you need and that's using data-* attribute:

    <div class="fruits" data-to="cat">apple</div>
    <div class="fruits" data-to="dog">banana</div>
    

    jQuery:

    $(".fruits").text(function(i){
      return $(this).data().to;     // or use: // this.dataset.to;
    });
    

    jsBin demo