sm1l3y sm1l3y - 2 months ago 11
jQuery Question

Convert JQUERY function into native JavaScript

I have been attempting to convert a JQUERY function into JavaScript. I am not sure what I am doing wrong. The values returned when I rewrote the function in JS all return 0.0.

Here is the JQUERY code I am wanting to convert to pure JavaScript:

$('#tableID > tbody > tr > td:nth-child(' + starter + ')').each(function () {
getAverage('#tableID > tbody > tr > td:nth-child(' + starter + ')', 'subTotal');
})


Basically I want to remove the .each() and use native JavaScript instead...

Here is the full code:

var el1 = $('#tableID > thead > tr > th:gt(17):not(.totalRow)');
var x = el1.length;
var starter = 19;
for (i = 0; i < x; i++) {
$('#tableID > tbody > tr > td:nth-child(' + starter + ')').each(function () {
getAverage('#tableID > tbody > tr > td:nth-child(' + starter + ')', 'subTotal');
})
starter += 1;
}


Here is the getAverage function to help understand what is happening:

//average function
function getAverage(a, b) {
var $this, $content, tdTxt, theAvg;
var sum = 0;
var count = 0;
$(a).each(function () {
$this = $(this); // cache $(this)
$content = $this.html();
tdTxt = parseFloat($this.text(), 10) || 0;
if ($this.hasClass(b)) {
theAvg = parseFloat((sum / count), 10) || 0;
$this.text((theAvg).toFixed(2));
sum = 0;
count = 0;
} else {
sum += parseFloat(tdTxt);
if ($content == '') {
}
else {
++count; // this micro-optimization makes it marginally faster
}
}
})
}

Answer

ESNext code

Array.from(
  document
    .querySelectorAll('#tableID > tbody > tr > td:nth-child(' + starter + ')')
  ).forEach(_=> getAverage(
    '#tableID > tbody > tr > td:nth-child(' + starter + ')',
    'subTotal'
  ))