Home > OS >  Equivalent of attaching a listener to buttons on document ready in jQuery instead of vanilla JavaScr
Equivalent of attaching a listener to buttons on document ready in jQuery instead of vanilla JavaScr

Time:05-22

How do I convert this JavaScript code to jQuery code?

if (document.readyState == 'loading') {
    document.addEventListener('DOMContentLoaded', ready)
} else {
    ready()
}

function ready() {
    var removeCartItemButtons = document.getElementsByClassName('btn-danger')
    for (var i = 0; i < removeCartItemButtons.length; i  ) {
        var button = removeCartItemButtons[i]
        button.addEventListener('click', removeCartItem)
    }
}

CodePudding user response:

Running something when the document is ready is handled by the $( document ).ready() method.

getElementByClassName can be replaced by a Class Selector (".class")

Your for loop can be removed because with jQuery methods all are called on each returned element.

addEventListener can be replaced by .click().

Then your code is just three lines long:

$(function(){
    $('.btn-danger').click(removeCartItem)
});

CodePudding user response:

jQuery is a library of Javascript, and therefore nothing needs to be converted.

  • Related