简体   繁体   中英

When looping through an array how do I add/remove classes from elements that fit a specific criteria?

Below I have code that loops through a list of items and I want to remove a class "hazardous" from div class item-left if element.hazardous == no. The way I have it set up right now is not working and I'm wondering if it might be because I need to find a way to target the specific non hazardous array element.

What "hazardous" does in my CSS is it adds a solid red border if the hazardous class is active. Otherwise hide the red border.

function showProducts(items) {
    var itemsHTML = [];
    items.forEach(function(element) {
        var url = element.url ? element.url : 'http://placehold.it/100x100'
        itemsHTML.push('<li><div class="item-left hazardous" data-product-id="' + element.id + '"><p><span class = "prod-name">' +
            'Product: ' + element.product + '</p></span><span class="prod-loc">' +
            'Location: ' + element.location + '</span><span class="qty">' +
            'Quantity: ' + element.quantity + '</span></div>' +
            '<div class="item-right"><img src="' + url + '"></div></li>')
        if (element.hazardous == 'no') {
            $('.item-left').removeClass('hazardous')
        }
    });
    $('.results').html(itemsHTML) 
}

Instead of hardcoding the hazardous class in the first place, apply it conditionally before the markup is rendered to DOM:

function showProducts(items) {
var itemsHTML = [];
items.forEach(function(element) {
    var classes = ['item-left', element.hazardous === 'no' ? '' : 'hazardous'].join(' ').trim() 
    var url = element.url ? element.url : 'http://placehold.it/100x100'
  itemsHTML.push('<li><div class="' + classes + '" data-product-id="' + element.id + '"><p><span class = "prod-name">' +
    'Product: ' + element.product + '</p></span><span class="prod-loc">' +
    'Location: ' + element.location + '</span><span class="qty">' +
    'Quantity: ' + element.quantity + '</span></div>' +
    '<div class="item-right"><img src="' + url +
    '"></div></li>')
});
$('.results').html(itemsHTML)

One of the problems you were facing was that you were trying to remove a class from a DOM element that didn't yet exist - at that point it was still a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM