My html:
<div class="wrapper">
<div class="objects">House, Cat, Dog, Car</div>
</div>
<div class="wrapper">
<div class="objects">House, Cat, Car</div>
</div>
<div class="wrapper">
<div class="objects">Cat, Dog</div>
</div>
My script:
$('.wrapper > .objects').each(function() {
var objects = $(this).text();
var objectsSplit = objects.split(',');
// console.log(objectsSplit);
$(this).empty(); // remove old content
$.each(objectsSplit, function(index, value) {
$('.wrapper > .objects').append("<div>" + value + "</div>");
});
});
I want to wrap every "object" into a div and remove the ",".
What I want:
<div class="wrapper">
<div class="objects">
<div>House</div>
<div>Cat</div>
<div>Dog<div>
<div>Car</div>
</div>
</div>
<div class="wrapper">
<div class="objects">
<div>House</div>
<div>Cat</div>
<div>Car</div>
</div>
</div>
// and so on ...
With my script I can store them all in an array, but the "$.each(objectsSplit, function(index, value) ..." part doesn`t work - the script crashes. Whats my fail?
2 Answers 2
This issue is happening because you are trying to append the new divs to each $('.wrapper > .objects'), inside of the current objects you are looping over. You can fix it by caching the current $(this) like:
var $this = $(this);
and then using this jquery object for append like:
$this.append("<div>" + value + "</div>");
Instead of doing:
$('.wrapper > .objects').append("<div>" + value + "</div>");
DEMO:
$('.wrapper > .objects').each(function() {
var $this = $(this);
var objects = $this.text();
var objectsSplit = objects.split(',').map(s => s.trim());
$this.empty(); // remove old content
$.each(objectsSplit, function(index, value) {
$this.append("<div>" + value + "</div>");
});
});
.wrapper > .objects { border:2px solid green; margin: 5px; padding:5px 10px;}
.wrapper > .objects > div { background-color:#EEE;margin-bottom: 5px; padding:4px 10px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="objects">House, Cat, Dog, Car</div>
</div>
<div class="wrapper">
<div class="objects">House, Cat, Car</div>
</div>
<div class="wrapper">
<div class="objects">Cat, Dog</div>
</div>
1 Comment
You can keep your current element and append to it as bellow:
$('.wrapper > .objects').each(function() {
const currentEl = this
var objects = $(this).text();
var objectsSplit = objects.split(',');
// console.log(objectsSplit);
$(this).empty(); // remove old content
$.each(objectsSplit, function(index, value) {
$(currentEl).append("<div>" + value + "</div>");
});
});
.wrapper {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="objects">House, Cat, Dog, Car</div>
</div>
<div class="wrapper">
<div class="objects">House, Cat, Car</div>
</div>
<div class="wrapper">
<div class="objects">Cat, Dog</div>
</div>
the script crashesand what is the error message?