user7087446 user7087446 - 1 month ago 8
jQuery Question

jquery selector does not work on dynamic content for loop output

I have set up a for loop which outputs a dynamic content, but it does not select some specific class as you might see in the jQuery part just below the for loop. But the this selector would not work. If I select the class directly it would, but adding the this selector it would not work anymore. Anyone who knows how to fix this in jQuery?



function renderSmartphones() {
var newContent = "";
for(var i = 0; i < smartphones.length; i++) {
newContent += "<div class='col-lg-4 col-md-4 col-sm-4 col-xs-12 box item'>";
newContent += "<div class='rom'>" + smartphones[i].rom + "</div>";
newContent += '<img src="' + smartphones[i].image + '" ';
newContent += "class='image'";
newContent += "alt='" + smartphones[i].alt_image + "' />";
newContent += "<button class='add-to-cart' type='button'>" + "add to cart" + "</button>";
newContent += "</div>";
}
$("#mobile").html(newContent);
}


$(document).on("click", ".add-to-cart", function() {
$(this).parent(".rom").find("img").css("border", "1px solid red);
$(this).find(".item").css("border", "1px solid red");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
<div id="wrapper">
<span><i id="shopping-cart" alt="shopping-cart-icon"></i></span>

<div id="mobile"></div>
</div>
</body>




Answer

Your selector and delegated event handler is working fine; the main issue is with your DOM traversal. The button is not a parent of .item, so find() won't work. Also note that you should define your styles in an external CSS file and add/remove classes as required. Adding inline CSS is a bad idea. Finally, your string concatenation was broken due to inconsistent quotes. Try this fixed version:

var smartphones = [{
  rom: 'rom1',
  image: 'image1.jpg',
  alt_image: 'alt_image1.jpg'
}, {
  rom: 'rom2',
  image: 'image2.jpg',
  alt_image: 'alt_image2.jpg'
}];

function renderSmartphones() {
  var newContent = "";
  for (var i = 0; i < smartphones.length; i++) {
    newContent += '<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12 box item">';
    newContent += '<div class="rom">' + smartphones[i].rom + '</div>';
    newContent += '<img src="' + smartphones[i].image + '" class="image" alt="' + smartphones[i].alt_image + '" />';
    newContent += '<button class="add-to-cart" type="button">add to cart</button>';
    newContent += '</div>';
  }
  $("#mobile").html(newContent);
}

$(document).on("click", ".add-to-cart", function() {
  $(this).closest(".item").addClass('active').find("img").addClass('active');
});

renderSmartphones();
.active {
  border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div id="wrapper">
    <span><i id="shopping-cart" alt="shopping-cart-icon"></i></span>

    <div id="mobile"></div>
  </div>
</body>