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 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.
Share Improve this question edited Sep 11, 2021 at 7:33 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Aug 19, 2016 at 8:03 beginnerbeginner 2,5084 gold badges32 silver badges54 bronze badges 10- 7 can you try this.style.display = 'none'; inside click event – Janani Kumar Commented Aug 19, 2016 at 8:08
- 21 "I was wondering is their any way to generate same effect using javascript" - nope, it only works with jQuery, which uses dark magic. – Alex Commented Aug 19, 2016 at 8:20
- Related, but probably not a dupe: stackoverflow.com/q/8801099/1075247 – AncientSwordRage Commented Aug 19, 2016 at 11:48
- I want to avoid jquery. but i think their is no easy way to get same effect using javascript. so i think i should use jquery instead of writing complex javascripts. – beginner Commented Aug 19, 2016 at 11:59
- 5 @Bergi i thought the sarcasm was obvious – Alex Commented Aug 19, 2016 at 12:57
8 Answers
Reset to default 21You 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
As Alex wrote in comments:
I was wondering if there is any way to generate same effect using JavaScript.
Nope, it only works with jQuery, which uses dark magic.
jQuery is misusing this
. In fact it should be used only in classes, not in callbacks.
To achieve the same effect using native DOM:
- Use
document.querySelectorAll()
to select all<p>
elements. - Convert the result (
NodeList
) to an array usingArray.from()
. - Call the
forEach()
method to execute a function on all elements. - Assign a
click
event listener to each element usingaddEventListener()
method. - Finally, inside the event listener, assign
'none'
toel.style.display
to hide the element.
Live demo
Array.from(document.querySelectorAll("p"))
.forEach(el => el.addEventListener('click', () => el.style.display = 'none'))
<p>Try clicking any of the paragraphs.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla purus metus, ullamcorper tempus augue interdum, efficitur vulputate lectus.</p>
<p>Vestibulum ullamcorper ultrices egestas.</p>
<p>Pellentesque volutpat, est ut convallis interdum, elit metus dapibus ex, non consectetur sem est et felis.</p>
Step1: Get all Paragraphs
Step2: Attach a clickListener to each item in Paragraphs
<html>
<head><title>Test</title></head>
<body>
<p>This is a paragraph</p>
<p>This is another paragraph</p>
</body>
<script type="text/javascript">
function paragraphsClickHandler() {
this.style.display = "none";
}
var paragraphs = document.getElementsByTagName("p");
var i;
for(i=0; i<paragraphs.length; i++)
paragraphs[i].addEventListener("click", paragraphsClickHandler);
</script>
</html>
If you happen to prefer arrow functions or cannot trust this
for some reason, you can grab e.currentTarget instead:
const elems = document.getElementsByTagName("p");
const handleClick = e => console.log(e.currentTarget); //logs the clicked element
for (let i = 0; i < elems.length; i++) {
elems[i].addEventListener('click', handleClick);
}
The method document.getElementByTagName
does not exist.
You should use document.getElement**s**ByTagName
instead which returns a collection:
document.getElementsByTagName("p")[0].onclick = function(){
this.style.display= "none";
}
Or use this for the same $("p")
example:
var elems = document.getElementsByTagName("p");
for(var i = 0; i < elems.length; i++){
elems[i].onclick = function(){
this.style.display= "none";
}
}
var bubblingToEle = function (target, type, value) {
while(target){
switch (type){
case 'nodeName':
if(target.nodeName === value){
return target;
}
break;
default :
break;
}
target = target.parentNode;
if(target.nodeName === 'HTML'){
break;
}
}
return null;
}
document.body.addEventListener('click', function (e) {
var target = e.target,
isPTag = bubblingToEle(target, 'nodeName', 'P');
if(isPTag){
isPTag.style.display = 'none';
}
})
I think this is better, no need to bind many listeners.
document.getElementsByTagName("p") returns a collection. You need to iterate and hook the event on each element as:
Array.prototype.slice.call(document.getElementsByTagName("p"))
.forEach(function(element) {
element.onclick = function() {
element.style.display = 'none';
}
});
Since you are using getElementsByTagName, it will give an array object, not a single element, so you need to iterate it in a loop and bind the click event with every element as below:
var domLength = document.getElementsByName('p').length;
for (var i=0; i<domLength; i++) {
document.getElementsByName('p')[i].style.display = none;
}