Reputation: 1699
I am trying to change the innerHTML of my page to become the innerHTML of the element I click on. The only problem is that I want it to take the whole element such as:
<section
class="homeItem">
<div>
<!-- more HTML here -->
</div>
</section>
Whereas the code that I have written in Javascript:
function selectedProduct(event){
target = event.target;
element = document.getElementById("test");
element.innerHTML = target.innerHTML;
}
will target the specific element that I click on.
What I would like to achieve is when I click on anywhere in the <section>
element, that it will take the innerHTML of the whole <section>
element, rather than the specific one that I have clicked.
I would presume it is something to do with selecting the parent element of the one that is clicked, but I am not sure and can't find anything online.
If possible, I would like to stay away from JQuery.
Upvotes: 156
Views: 356729
Reputation: 1
Yep, I did it by targeting event.target.parentNode
. You can also chain that to go higher up your DOM tree, ie event.target.parentNode.parentNode
.
Upvotes: 0
Reputation: 51
You can use closest()
to get your desired ancestor/parent:
const target = event.target;
const parent = target.closest('section');
Upvotes: 5
Reputation: 9
$(document).on("click", function(event){
var a = $(event.target).parents();
var flaghide = true;
a.each(function(index, val){
if(val == $(container)[0]){
flaghide = false;
}
});
if(flaghide == true){
//required code
}
})
Upvotes: 0
Reputation: 158
var _RemoveBtn = document.getElementsByClassName("remove");
for(var i=0 ; i<_RemoveBtn.length ; i++){
_RemoveBtn[i].addEventListener('click',sample,false);
}
function sample(event){
console.log(event.currentTarget.parentNode);
}
Upvotes: 0
Reputation: 7591
I think what you need is to use the event.currentTarget
. This will contain the element that actually has the event listener. So if the whole <section>
has the eventlistener event.target
will be the clicked element, the <section>
will be in event.currentTarget
.
Otherwise parentNode
might be what you're looking for.
link to currentTarget
link to parentNode
Upvotes: 283
Reputation: 346
function getParent(event)
{
return event.target.parentNode;
}
Examples: 1.
document.body.addEventListener("click", getParent, false);
returns the parent element of the current element that you have clicked.
- If you want to use inside any function then pass your event and call the function like this :
function yourFunction(event){ var parentElement = getParent(event); }
Upvotes: 13
Reputation: 5984
To use the parent of an element use parentElement
:
function selectedProduct(event){
var target = event.target;
var parent = target.parentElement;//parent of "target"
}
Upvotes: 87