Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use this in JavaScript?

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.

like image 611
beginner Avatar asked Aug 19 '16 08:08

beginner


People also ask

How can I use this in JavaScript?

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.

What is this _ in JavaScript?

The _ is a JavaScript identifier, probably for the underscore library in this case.

Should you use this in JavaScript?

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.

Can you use this in an object JavaScript?

“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.


1 Answers

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

like image 146
Milind Anantwar Avatar answered Sep 21 '22 08:09

Milind Anantwar