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!");
});
}
}
The Javascript code is too bulky, is there a way where I can select a tag by its name and write the code as -
"If any 'p' tag is clicked, alert('click successful')"
instead of looping through all the <p></p>
tags?
Any alternative way using tag name?
You can use event 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/
jQuery is "less code" because you're calling a pre-written function. Don't want to use jQuery? Then write your own functions.
function addEventToElements(tagname,handler) {
var elems = document.getElementsByTagName(tagname);
for(var i = 0, l = elems.length; i<l; i++) {
elems[i].addEventListener('click',handler);
}
}
Now in your actual code, you can just write:
addEventToElements('p',function() {alert("click succeeded");});
Congratulations, you have re-invented jQuery.
... Or not, because the reason jQuery is so popular is that it does a lot more. Things like normalising browser support (for those that use attachEvent
or the old onEventName
handlers) are half the reason jQuery exists, and you'd have to account for all of them in your own re-invention ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With