Could this function be shortened?
`
$(function () {
let section1 = $('.amount_1').attr('data-product_id');
let section2 = $('.amount_2').attr('data-product_id');
let section5 = $('.amount_5').attr('data-product_id');
let section10= $('.amount_10').attr('data-product_id');
let section15 = $('.amount_15').attr('data-product_id');
let $link1 = $("#" + section1).find('a').clone().text('');
if ($link1.length > 0) {
$('.col1').removeAttr("href").removeClass("single").wrap($link1).addClass("active");
}
let $link2 = $("#" + section2).find('a').clone().text('');
if ($link2.length > 0) {
$('.col2').removeAttr("href").removeClass("single").wrap($link2).addClass("active");
}
let $link5 = $("#" + section5).find('a').clone().text('');
if ($link5.length > 0) {
$('.col5').removeAttr("href").removeClass("single").wrap($link5).addClass("active");
}
let $link10 = $("#" + section10).find('a').clone().text('');
if ($link10.length > 0) {
$('.col10').removeAttr("href").removeClass("single").wrap($link10).addClass("active");
}
let $link15 = $("#" + section15).find('a').clone().text('');
if ($link15.length > 0) {
$('.col15').removeAttr("href").removeClass("single").wrap($link15).addClass("active");
}
});
`
Maybe in a for loop? I don’t really know how cause the numbers are random.
Thanks in advance
2
Answers
If you have access to change the HTML, I would personally recommend that you change it use a single class that can be gathered in a single go… and move the
amount
to it’s own data attributeFor example,
class="amount_1"
in your HTML would becomeclass="amount" data-amount="1"
etcPlease also note jQuery gives you the
.data()
method so you don’t need to useattr
It does not look so "random" for me, numbers
1, 2, 5, 10, 15
are pretty repetitive. Extract them and use them as a part of your jquery selectors.Something like this (upd, version with 1 loop only):