I'm trying to add an event handler on the document on the li selector. In JQuery, this will work:
$('li').click(function(){
var justify = $(this).attr('data-cid');
alert(justify);
});
how can I do the exact same thing in JavaScript?
I'm trying to add an event handler on the document on the li selector. In JQuery, this will work:
$('li').click(function(){
var justify = $(this).attr('data-cid');
alert(justify);
});
how can I do the exact same thing in JavaScript?
Try as follows.
var lis = document.getElementsByTagName('li');
for(var i = 0; i < lis.length; i++) {
(function(i) {
lis[i].addEventListener('click', function() {
alert(this.dataset.cid);
}, false);
})(i);
}
<ul>
<li data-cid="1">1</li>
<li data-cid="2">2</li>
<li data-cid="3">3</li>
<li data-cid="4">4</li>
<li data-cid="5">5</li>
</ul>
i is referred inside the function. here - jsfiddle.net/20u46bgh - code works without it as well.querySelector returns object that is the first element on document. At the same time querySelectorAll returns the array of all element of selector.This is more like what happens with jQuery.
it binds a single event to the window and checks to see what the event target is, if it finds a match it will fire the callback, with the context set as the clicked element.
const $ = function(selector) {
const listeners = {}
const bindListener = function(event) {
listeners[event] = []
window.addEventListener(event, function (e) {
// iterate through the subscribed events to find any matching selectors
const matches = listeners[event].filter(x => e.target.matches(x.selector))
if (matches) {
matches.forEach(x => x.cb.call(e.target, e))
}
})
}
// bind a single event listener to the window for each event type
bindListener('click')
bindListener('mouseover')
// return your api
return {
on(event, cb) {
listeners[event].push({ selector, cb })
},
off(event, cb) {
listeners = listeners[event].filter(x => x.cb !== cb)
}
}
}
$('li').on('click', function(e){
console.log(this.dataset.cid)
})
$('li:first-of-type').on('mouseover', function (e) {
console.log('mouseover first li', this.dataset.cid)
})
$('li:last-of-type').on('click', function (e) {
console.log('clicked last li', this.dataset.cid)
})
<ul>
<li data-cid="foo">foo</li>
<li data-cid="bar">bar</li>
<li data-cid="baz">baz</li>
</ul>
Use getElementsByTagName and addEventListener
That should do the trick if I'm understanding correctly.
You can use document.querySelectorAll("li"), for..of loop to iterate li elements, set event listeners; element.dataset to get data-* attribute value
for (let li of document.querySelectorAll("li")) {
li.addEventListener("click", function() {
let justify = this.dataset.cid;
})
}
Alternatively
var li = [].slice.call(document.querySelectorAll("li"));
li.forEach(function(el) {
el.addEventListener("click", function() {
var justify = this.dataset.cid;
})
})
lI...? Not defined.