0

I am slowly making my way from jQuery to vanilla JS, but I am struggling with wanting to write the following in JavaScript, would I have to setup a 'for' loop for each element? How would I target the child elements an an ID?

Here's what I would want to understand:

$('#id li').click(function(){
    $(this).addClass('active');
});

I understand document getElementById to grab the '#id' but how would I achieve getting the child <li> elements? And how would I get the 'onclick' function to work for ANY list element clicked? Would I have to setup a 'for' loop for each element? Any help much appreciated!

14
  • why you need move to thing you named vanilla js (DOM+language standard) ? The fact is not that jquery bad, fact that if you write library yourself there is 70% probability, that your library will work worse than jquery. and yes, you need loop through found elements. Check the jquery sources. to search use .querySelector dom function Commented Feb 2, 2013 at 21:40
  • 2
    That's what I am asking people to help? Did you understand my question? I am learning javascript over jQuery. Commented Feb 2, 2013 at 21:50
  • 1
    HTML and CSS constantly changes too. I don't see your point. Commented Feb 2, 2013 at 21:52
  • 2
    that is definitely arguable. if you really want to grasp on something, then learning about the internals isn't a waste of time. Commented Feb 2, 2013 at 21:53
  • 1
    Yes, learning how something works under the hood is never a waste of time. In this case learning how the DOM works is vital to being a good web dev. jQuery is a great library, but it never hurts to know what is happening under the hood. Commented Feb 2, 2013 at 22:09

3 Answers 3

2

Here is a JSFiddle that does what you want:
http://jsfiddle.net/digitalzebra/ZMXGC/10/

(function() {
    var wrapper = document.getElementById("id");
    var clickFunc = function(event) {
        var target = event.originalTarget || event.target;

        target.className = "active";
    };

    wrapper.addEventListener("click",clickFunc);
})();

A little bit of an explanation is in order...

First, I'm using a self executing function to fetch the wrapper div, using getElementById(). This is equivalent to using an id selector in jQuery: $('#id')

Next, I'm attaching a click handler to the element using the function addEventListener() and passing in an event type of click.

This binds the click handler function to the div element, the same as jQuery's click() would do. I'm using something called event bubbling, where a click event on any of the children of the wrapper will call the click handler attached to the wrapper.

Once the user clicks on the element, our function is called. originalTarget or target is the element that the user actually clicked in to, which in this case will always be an li. I'm then setting the class on that element to active.

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

8 Comments

Didn't he wanted li elements ?
Thanks @Polaris878 but this doesn't seem to be working for me?
I can't see where the <li> elements come into play here? Thanks for your post.
Change originalTarget to target
@Toddo, sorry my example is only working in FireFox right now, give me a sec and I'll get it working in Chrome as well.
|
1

Here is example for above question http://jsfiddle.net/G3ADG/2/

    (function() {
    var id = document.getElementById("id");
    var liele = id.getElementsByTagName("li");
    for (var i = 0; i < liele.length; i++) {
        liele[i].addEventListener("click", function () {
            this.className = "active";
        })

    }
})();

Well I really liked Polaris878 solution as he is not using any loop inside it. In my solution first get HTML node information using document.getElementById this works similarly to $("#id"). than in next step I am fetching all tag type of "li" which are children of "id", than on this li tag array adding event listener to listen click functionality

className is one of attribute that allow to add class on that Node

I have tested above code in mozilla and chrome

Comments

0

This will work (IE >= 10), not want to search classList.add() replacement for IE<10,

var elems = document.querySelectorAll('#id li');
for (var i = 0; i < elems.length; i++) {
    var elem=elems[i];
    elem.addEventListener("click", function (e) {

        this.classList.add('active');
    });
}

fiddle

4 Comments

no and this
I mean click several times
to acheive same resuts you need to implement hasClass, and finally you will write something that works like jquery
also, jquery add listener to document itself, not element

Your Answer

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