javascriptdomforeachthisdom-node

Calling function to only one div of a certain class using pure JS


as part of my learning process as front end developer, I have decided to produce a product without jQuery and instead use vanilla JavaScript to do all my interactions.

I want to call a function onClick and retrieve the positioning of only the DOM node I clicked which is part of a class. However I don't know how this would be done in pure JavaScript. Basically I want to replicate what $(this) does in jQuery.

Here is my code below so far:

function expand(name) {
    var elem = document.querySelectorAll(name)

for (var i = 0; i < elem.length; i++) {
    var rect = elem[i].getBoundingClientRect();
    console.log(rect.top, rect.right, rect.bottom, rect.left);
    }
}

document.querySelectorAll(".box").onclick = expand(this)

Thanks in advance and any other possible solutions to the problem are much appreciated.


Solution

  • function expand() {
        var rect = this.getBoundingClientRect();
        console.log(rect.top, rect.right, rect.bottom, rect.left);
    }
    
    function nodeListOn(list, type, handler, useCapture) {
        var i, t;
        type = type.split(/s+/);
        for (i = 0; i < list.length; ++i) {
            for (t = 0; t < type.length; ++t) {
                list[i].addEventListener(type[t], handler, useCapture);
            }    
        }
    }
    
    var nodes = document.querySelectorAll('.box');
    nodeListOn(nodes, 'click', expand);