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.

1
  • Where are you storing your Animals strings? Commented Jan 23, 2015 at 0:50

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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!

12 Comments

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")
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 :)
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
No doubt! jQuery serves as a great polyfill, but it's overused in my opinion, that's why I provided a jQuery-free solution :)
here, I've create a JS version that runs double faster than yours: jsperf.com/jquery-selector-vs-javascript/2 (since you're interested in JS versions ;) ) Might be useful! Cheers
|
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()" />

2 Comments

$('.fruits') is already a collection of elements. No need to .each() to modify the .text() or .html()
Your way is more concise. I'll add a note about it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.