Вам нужно удалить пробел, который предшествует или следует за содержимым элемента, и вы делаете это с помощью .trim()
.
Вам также нужно смотреть только на предыдущего брата, а не на всех братьев, потому что послеВы добавляете еще один div, он не будет содержать число, которое делает предыдущий, и после этого код никогда не найдет совпадения.
Наконец, вы должны использовать .text()
, а не .html()
, когда выпросматривают текстовое содержимое элемента, а не его дочернее HTML-содержимое.
$(document).ready(function() {
// This is only added to demonstrate that the following
// code works no matter what the number is in the div
let val = prompt("Pick a number");
$("div")[0].textContent = " " + val + " ";
// *****************************************************
let div = $('button').prev(); // Get a reference to the <div> just prior to the button
let num = +div.text().trim(); // Get the text content of that <div> and convert to number
$('button').click(function() {
// Loop the amount of times as was in the <div>
for(var i = 0; i < num; i++) {
// Create a new <div> with an id of the current loop index
$('body').append('<div id=' + i + '>' + 'My div' + '</div>');
}
// Show newly created code (scroll to bottom of results to see)
console.log($("body").html());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
</div>
<button type="button">Add</button>