Equivalent to jQuery code in Javascript

This is the jQuery code I have

$('p').click(function(){
    alert("click successful!");
});

This is the JS code I could come up with

window.onload = function() {
    var para = document.getElementsByTagName('p');
    for(var i = 0; i < para.length; i++) {
        para[i].addEventListener('click',function(){
            alert("click successful!");
        });
    }
}

Javascript code is too cumbersome, there is a way in which I can select a tag by its name and write the code as -

"If you click on any tag 'p', click" alert "(" click "successfully")

instead of iterating over all tags <p></p>? Any alternative way to use a tag name ?

+4
source share
4 answers

You can use delegation delegation - add a click handler to a higher level element and check event.target

document.body.addEventListener("click", function(e) {
    if (e.target.tagName.toLowerCase() == "p") alert("click succeeded");
});

Demo: http://jsfiddle.net/jdkr3sch/

+7

jQuery - " ", . jQuery? .

function addEventToElements(tagname,handler) {
    var elems = document.getElementsByTagName(tagname);
    for(var i = 0, l = elems.length; i<l; i++) {
        elems[i].addEventListener('click',handler);
    }
}

:

addEventToElements('p',function() {alert("click succeeded");});

, jQuery.

... , jQuery , . , ( , attachEvent onEventName), , jQuery, ;)

+3

.

document.addEventListener('DOMContentLoaded', function() {
    document.body.addEventListener('click', function(evt) {
        if (evt.target.matches('p, p *')) alert('Paragraph clicked!');
    }, false);
}, false);

:

1) , . , , N , , , , , , .

2) DOMContentLoaded, window.onload - (), jQuery DOM.

3) matches() - http://caniuse.com/#feat=matchesselector

+3

:

document.querySelectorAll('p')

( p).

AFAIK $('p')


addEventListener('click',function(){alert("click successful!")}

to add a click handler to one element.


to mimic an array, you can use [].slice.calldom in the collection of elements (this way you use the method .forEach()).


together:

[].slice.call(document.querySelectorAll('p')).
forEach(function(x){x.addEventListener('click',
    function(){alert("click successful!")
})})

https://jsfiddle.net/maio/m861hbmh/

+1
source

Source: https://habr.com/ru/post/1613100/


All Articles