user6733315 user6733315 - 3 months ago 7
HTML Question

How to use this in JavaScript?

In jQuery we use :

$("p").click(function(){$(this).hide();});


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

Answer

You need to iterate over each element and then use addEventListener to attach 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

Comments