Fjott
Fjott

Reputation: 1137

Convert JS function to jQuery

How can this JavaScript function

function reset() {
    var customSelect = document.getElementsByClassName("custom-select")[0];
    var select = customSelect.getElementsByTagName("select")[0];
    var selected = customSelect.getElementsByClassName("select-selected")[0];
    var selectedItem = customSelect.getElementsByClassName('same-as-selected')[0];

    select.selectedIndex = 0;
    selected.innerHTML = select.options[select.selectedIndex].innerHTML;
    selectedItem.classList.remove('same-as-selected');
}

Be converted into a jQuery function? I have tried the first variable like this:

  var customSelect = document.getElementsByClassName("custom-select")[0];
  var jqcustomSelect = $(".custom-select:eq(0)").html();
  console.log(customSelect + "  JQ: " + jqcustomSelect);

But I am confused about the output:

customSelect = [object HTMLDivElement]

While

jqcustomSelect = html code

1) How can I convert this function?

2) And why is the customSelect output [object HTMLDivElement], while the de outputs html code?

Upvotes: 0

Views: 296

Answers (1)

Alex197
Alex197

Reputation: 923

Your JQuery function should be like this

function reset(){
    var customSelect = $('.custom-select');
    var select = customSelect.find('select');
    select.prop('selectedIndex', 0);
    customSelect.find('.select-selected').html(select.find('option:selected').html());
    customSelect.find('.same-as-selected').removeClass('same-as-selected');
}

Try this, but i'ts not easy to test it without your source code

Upvotes: 1

Related Questions