0

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?

6
  • @HarishKommuri what are you referring to? Commented Mar 26, 2017 at 2:23
  • Technically it is JavaScript... Commented Mar 26, 2017 at 2:23
  • @epascarello it's JQuery. Commented Mar 26, 2017 at 2:23
  • Which is JavaScript Commented Mar 26, 2017 at 2:23
  • 1
    So you need to use querySelectorAll or getElementsByTagName, for loop, addEventListener, and getAttribute Commented Mar 26, 2017 at 2:26

4 Answers 4

2

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>

Sign up to request clarification or add additional context in comments.

6 Comments

This solved everything. Thank you my indian friend. Approved for best answer.
You don't need that IIFE. It is only useful when i is referred inside the function. here - jsfiddle.net/20u46bgh - code works without it as well.
@Gaurang Tandon, querySelector returns object that is the first element on document. At the same time querySelectorAll returns the array of all element of selector.
@HarishKommuri That was a typo, sorry for that, but it wasn't my point. I was talking about the IIFE.
@HarishKommuri how can I get the className of the clicked element?
|
1

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>

Comments

0

Use getElementsByTagName and addEventListener

That should do the trick if I'm understanding correctly.

Comments

0

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;
  })
})

7 Comments

What is lI...? Not defined.
@epascarello Are you referencing .dataset at ie?
@guest271314 slice is not safe on arguments
@WayneXMayersX Not sure what you mean concerning .slice()? Can you share further details?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.