In jQuery we use:
$("p").click(function(){$(this).hide();});
In the above statement this
is very important, because it hides only that p
element on which we click. But instead if we use "p"
at the place of this
it will hide all the p
elements when we click any one of the p
element.
I was wondering if there is any way to generate same effect using JavaScript. I tried:
document.getElementsByTagName("p").onclick = function(){this.style.display:none;}
and
document.getElementsByTagName("p").onclick = function(){document.getElementsByTagName(this).style.display:none;}
But none of this works.
In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.
The _ is a JavaScript identifier, probably for the underscore library in this case.
The best way to avoid this related problems is to not use this at all. JavaScript without this can be a better functional programming language. We can build encapsulated objects, without using this , as collections of closures. With React Hooks we can create this -less stateful components.
“this” is not bound In JavaScript, keyword this behaves unlike most other programming languages. It can be used in any function, even if it's not a method of an object. The value of this is evaluated during the run-time, depending on the context. The rule is simple: if obj.
You need to iterate over each element and then use addEventListener
to attach an event to it:
var allP = document.getElementsByTagName("p");
for(i=0; i< allP.length; i++) {
allP[i].addEventListener('click', function () {
this.style.display = "none";
});
}
Working Demo
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