You first need to .find the .string inside the .item being iterated over with
var arr = $(this).find(".string").text().split(" ");
else your $(".string") will only match the first .string in the document. Then, to set the child .string of the .item being itearted over, use
$(this).find(".string").html(html);
(closest searches ancestors, not children)
Also make sure not to implicitly create a global variable with
for (i = 0; i < arr.length; ++i) {
(always declare variables you're going to use with const, let, or var)
$(".item").each(function() {
var arr = $(this).find(".string").text().split(" ");
var html = "";
for (let i = 0; i < arr.length; ++i) {
html += "<span>" + arr[i] + "</span>";
}
$(this).find(".string").html(html);
});
.string span {
border: 1px solid
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">
<div class="string">Test1 Test2 Test3</div>
</div>
<div class="item">
<div class="string">TestA TestB TestC</div>
</div>
Or, if possible, you might iterate over the .strings directly:
$(".string").each(function() {
var arr = $(this).text().split(" ");
var html = "";
for (let i = 0; i < arr.length; i++) {
html += "<span>" + arr[i] + "</span>";
}
$(this).html(html);
});
.string span {
border: 1px solid
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">
<div class="string">Test1 Test2 Test3</div>
</div>
<div class="item">
<div class="string">TestA TestB TestC</div>
</div>
Another option would be to use a regular expression replace - find non-space characters ((\S+)), and replace with those matched non-space characters surrounded by a span: <span>$1</span>:
$(".string").each(function() {
$(this).html(
$(this).html().replace(/(\S+)\s*/g, '<span>$1</span>')
);
});
.string span {
border: 1px solid
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">
<div class="string">Test1 Test2 Test3</div>
</div>
<div class="item">
<div class="string">TestA TestB TestC</div>
</div>