3

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.

Manuel Allenspach
  • 12,467
  • 14
  • 54
  • 76
Qamelion
  • 69
  • 1
  • 1
  • 8

3 Answers3

8

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

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
3

Roko provided an answer in jQuery, with that out of the way..

There is no need to use jQuery for such a simple task, here is one in plain JavaScript. (fiddle)

var pets = [ "cat", "dog","fish" ];
var fruits = document.querySelectorAll(".fruits"); // Partial support in IE8
for( var i = 0 ; i < fruits.length ; i ++ )
    fruits[i].innerHTML = pets[i];

Here is an even faster version by @Roko.

var pets = [ "cat", "dog", "fish" ],
    fruits = document.getElementsByClassName("fruits"), // Not supported in IE8
    tot = fruits.length,
    i = 0;
for(;i<tot;) fruits[i].innerHTML = pets[i++];

Benchmark jQuery vs JavaScript vs Roko's JavaScript

Hope it helps!

Community
  • 1
  • 1
undefined
  • 3,949
  • 4
  • 26
  • 38
  • Well, jQuery *is* JavaScript, and inside the Sizzle function `selector` it already uses the JS's (guess what!) `querySelectorAll` to create a collection of Elements objects and all it takes is `$(".fruits")` – Roko C. Buljan Jan 23 '15 at 01:11
  • I never said jQuery *wans't* javascript, I said my answer is in plain javascript (no libraries), I also pointed out that you gave an answer in jQuery, so that my answer only counts as an addition or another solution to the problem. I believe my answer is more efficient, while being somewhat more tedious to write :) – undefined Jan 23 '15 at 02:41
  • JS will be always faster than jQ, agreed with that, but jQ will help you move with your project and don't care about IE8's partial support of `querySelector / querySelectorAll` – Roko C. Buljan Jan 23 '15 at 02:46
  • No doubt! jQuery serves as a great polyfill, but it's overused in my opinion, that's why I provided a jQuery-free solution :) – undefined Jan 23 '15 at 02:49
  • here, I've create a JS version that runs double faster than yours: http://jsperf.com/jquery-selector-vs-javascript/2 (since you're interested in JS versions ;) ) Might be useful! Cheers – Roko C. Buljan Jan 23 '15 at 02:53
  • I thought about it, but I went to a more logic-friendly loop haha, I've added your version, thanks! :) – undefined Jan 23 '15 at 02:58
  • (The fancy `++` loop is just there cause I was bored) The main speed difference came out cause the use of `getElementsByClassName` :) – Roko C. Buljan Jan 23 '15 at 03:00
  • Ahh, yes I was curious about that, I'm doing a jsperf test for all the "getElementBy" methods! Thanks for the inspiration haha :) – undefined Jan 23 '15 at 03:03
  • Created an even faster one: (same Benchmark link /2 ) But again note that `getElementsByClassName` is not supported at all in IE8 :) – Roko C. Buljan Jan 23 '15 at 03:09
  • 5% faster by not defining/getting variables inside the loop, interesting, that's pretty cool haha – undefined Jan 23 '15 at 03:13
  • Exactly. P.S: sorry for my edit/intrusion. Just added the notes about IE8 compatibility and the newest JS code. See ya – Roko C. Buljan Jan 23 '15 at 03:16
  • No problem, always what's best for the asker! – undefined Jan 23 '15 at 03:27
1

Using .each would look something like this. I've set it to toggle back and forth using an array to hold the other collection. However, Roko C. Buljan's answer accomplishes essentially the same thing with less effort by avoiding some unnecessary method calls, so I would definitely say his is the better answer.

var otherVals = ['dog', 'cat', 'fish'];

function go() {
  $('.fruits').each(function(index) {
    var temp = $(this).html();
    $(this).html(otherVals[index]);
    otherVals[index] = temp;
  });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div class="fruits">apple</div>
  <div class="fruits">banana</div>
  <div class="fruits">strawberry</div>
</div>
<input type="button" value="go" onclick="go()" />
Mic
  • 3,810
  • 1
  • 13
  • 16