skip to Main Content

So, i have the following jQuery code which targets some DOM elements,i want to change the code into a switch statment but i cannot find a way to do it,anyone has any ideeas or can give me a model to do it?

if ($('.similar-products')) {                                       
    $('.similarproducts').append(iframe_html);
} 

if ($('.partial--product')){
    $('.partial--product').append(iframe_html);
}

if ($('.product-page')){
    $('div.product-page').append(iframe_html);
}

if($('#section-product-page')){
   $('#section-product-page').append(iframe_html);
}
//needs fix
if($('.swatch-product-id-*')){
   $('.swatch-product-id-*').append(iframe_html);
}

if($('.product__tabs')){
   $('.product__tabs').append(iframe_html);
}
if($('.main-content-wrapper')){
   $('.main-content-wrapper').append(iframe_html);
}

if($('#shopify-section-product-description-bottom-template')){
   $('#shopify-section-product-description-bottom-template').append(iframe_html);
}
if($('.product-details-inline')){
   $('.product-details-inline').append(iframe_html);
}

if($('.social-footer')){
   $('.social-footer').prepend(iframe_html);
}
if($('.section-related-products')){
   $('.section-related-products').append(iframe_html);
}

if($('.product-details')){
   $('.product-details').append(iframe_html);
}

2

Answers


  1. it would be even easier than a switch in this case a loop iterating over an array:

    let selectors = [
        '.similar-products',
        '.partial--product',
        ... ]
    
    
    selectors.forEach(x => {
        if($(x).length > 0) {
            $(x).append(iframe_html)
        } 
    })
    
    Login or Signup to reply.
  2. Something like this might be easier.

    var elements = [
        '.similar-products',
        '.partial--product',
        '.product-page',
        '#section-product-page',
        '.swatch-product-id-*',
        '.product__tabs',
        '.main-content-wrapper',
        '#shopify-section-product-description-bottom-template',
        '.product-details-inline',
        '.social-footer'
    ];
    
    elements.forEach(element => {
        if($(element)){
            $(element).append(iframe_html);
        }
    });
    

    From what I could tell you’re doing the same thing in each if statement. Creating an array of strings with your jquery selectors and run the same function on them. Switch statement ‘might’ be better than a load of if statements, but this way makes it easier, to add or remove the check and append.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search