I am practising event delegation and I stumbled upon this. I have 4 paragraphs setting inside an article tag which sits in a div. I want to apply a .green class that changes background of each paragraph ONLY when I click on it. However the green class gets only applied up to the parent (article) and the grandparent (div) as well. Tell me what's wrong with my code please.
function paintParagraph(e) {
if (!e) {
e = window.event;
}
var target, parent;
target = e.target || e.srcElement;
parent = target.parentNode;
parent.className = 'green';
e.stopPropagation();
}
var paragraphList = document.querySelector('#p-list');
paragraphList.addEventListener('click', function(e) {
paintParagraph(e);
}
, false);
p {
padding: 10px;
margin: 20px;
border: 2px solid;
line-height: 1.5em;
letter-spacing: 0.2em;
text-align: center;
}
.green {
background-color: green;
}
<div id="main">
<article id="p-list">
<p class="para">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vitae perferendis culpa velit excepturi iste reprehenderit quaerat debitis repudiandae itaque beatae. Numquam dolorum ducimus iusto temporibus facilis error possimus amet, illo.</p
><p class="para2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vitae perferendis culpa velit excepturi iste reprehenderit quaerat debitis repudiandae itaque beatae. Numquam dolorum ducimus iusto temporibus facilis error possimus amet, illo.</p
><p class="para3">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vitae perferendis culpa velit excepturi iste reprehenderit quaerat debitis repudiandae itaque beatae. Numquam dolorum ducimus iusto temporibus facilis error possimus amet, illo.</p
><p class="para4">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vitae perferendis culpa velit excepturi iste reprehenderit quaerat debitis repudiandae itaque beatae. Numquam dolorum ducimus iusto temporibus facilis error possimus amet, illo.</p
></article>
</div>
You should check if the clicked target is p then only proceed further.
Now you will have only p element as the target apply the class on it.