user3907336
user3907336

Reputation: 31

How can I convert this JQuery into vanilla Javascript?

hello there i have been trying for the last few day to convert all my jquery into vanilla javascript and this is one of the few that i am having the problems with

 $(".book").click(function(){
    var timeslot = $(this).attr('data-timeslot');
    $("#slot").html(timeslot);
    $("#timeslot").val(timeslot);

})

this is what i have come up with so far and dont even know if i have started converting this correctly

var book = document.querySelector(".book");
book.addEventListener('click', function() {

  var timeslot = book.getAttribute('data-timeslot');
  document.getElementById("slot").innerHTML = timeslot;


}());

question is am i along the right lines or am heading the wrong direction

Upvotes: 0

Views: 227

Answers (2)

samurai_code
samurai_code

Reputation: 67

var books = document.getElementsByClassName("book");
books.forEach( function(book) {
   book.addEventListener('click', function() {

   var timeslot = book.getAttribute('data-timeslot');
   document.getElementById("slot").innerHTML = timeslot;

  });
});

Upvotes: 0

duc mai
duc mai

Reputation: 1422

it is almost correct, except select should take all matches

var books = document.querySelectorAll(".book");
[...books].forEach(book => {
   book.addEventListener('click', function() {

   var timeslot = book.getAttribute('data-timeslot');
   document.getElementById("slot").innerHTML = timeslot;
  });
})

Upvotes: 1

Related Questions