How to add a function in js to a html element – which only made in js?

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error How to add a function in js to a html element – which only made in js? on this date .

I would like to change a row’s background-color in a table, if I select an object of a “select”‘s list, but only if this element, which is a number is even. But the main problem is that the “object” is made in js, so that is not in the html file, so I couldn’t add to the objects an onclick function, which could make the background-color of the row change. Please help, I’ve lost.


        <select class = "form-select, col-6" id="quantiti" onclick = "ifSelectedLetHeadChange()" >
        This was the original version that I copied:
        <select class="form-select, col-6" id="quantiti" 


        function quantity(amount) {
                var select = document.getElementById('quantiti');
            for (var i = 0; i < amount; i++) {
            select.options[select.options.length] = new Option(i + 1, i);
                select.options[select.options.index] = i+1 ;

        function ifSelectedOptionLetTrChange(value) {
            if (option.value % 2 ) {
                $("tr").css("background-color", "lightblue");
        } else {
                $("tr").css("background-color", "blue");


It seems that you are working with JQuery. You can do it with plain JS or with JQuery.


It is advised to work with the change event instead of a click event. The change event however will only trigger on a change. I will do it with the change for this.

var select = $("#quantiti");
var tr = $("tr");

select.on('change', function() {
  var value = $(this).val();

function setTrColor(value) {
  tr.css("background-color", value % 2 ? "lightblue" : "blue");


var select = document.getElementsById("quantiti");
var tr ="tr"));

select.addEventListener("change", function(event) {
  var targetElement = || event.srcElement;
  var value = targetElement.value;

function setTrColor(value) {
  tr.forEach(function(element){ = value % 2 ? "lightblue" : "blue";