vue Recursively Gets the Element Instance of the Parent Element
- 2021-08-06 19:54:01
- OfStack
Use recursion to find the parent element until the desired element is found, and then return
getParentTag(startTag) {
var self = this;
// Is the incoming label DOM Object
if (!(startTag instanceof HTMLElement)) return;
// Whether the parent label is body, To stop returning to the collection , On the contrary, continue
let nodeName = "";
if (startTag.parentElement) {
nodeName = startTag.parentElement.nodeName ? startTag.parentElement.nodeName : "";
} else {
return;
}
if ("BODY" !== nodeName) {
if (nodeName == "TD") {
return startTag.parentElement;
} else {
if (startTag.parentElement.parentElement) {
return self.getParentTag(startTag.parentElement);
} else {
return false;
}
}
}
}
Call function
this.getParentTag(event.target);
Additional knowledge: Vue. js How to get sibling, child, and parent elements (DOM operation)
I won't talk too much, let's look at the code ~
<button @click = " clickfun($event) " > Click </button>
methods: {
clickfun(e) {
// e.target Is the element you are currently clicking on
// e.currentTarget Is the element that you bind to the event
# Get the preceding of the clicked element 1 Elements
e.currentTarget.previousElementSibling.innerHTML
# Get the number of the clicked element 1 Child element
e.currentTarget.firstElementChild
# Get the following of the click element 1 Elements
e.currentTarget.nextElementSibling
# Get the click element in id For string Elements of
e.currentTarget.getElementById("string")
# Object of the clicked element string Attribute
e.currentTarget.getAttributeNode('string')
# Get the parent element of the clicked element
e.currentTarget.parentElement
# Get the preceding of the clicked element 1 The first of the elements 1 Child element of HTML Value
e.currentTarget.previousElementSibling.firstElementChild.innerHTML
}
},