can I query select the Parent from child in Javascript?

Viewed 40

how to use querySelector to select the parent element from the child?

in my example the HTML structure is like this:

<label>
  <input/> <!-- I know only this -->
</label>

and in html what I know is only the child so input.

how can get the parent from child input, so getting the label.


from what I know is easy to get the child from the parent by doing like this parent > child

is there any child < parent? (similar logic).


if isn't possible with querySelector() is there any other way with the javascript API?

3 Answers

use .parentElement or use .closest()

parentElement: https://developer.mozilla.org/en-US/docs/Web/API/Node/parentElement

if you want only the parent element.

closest: https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

if you want specific tag (this can make you some bugs if not used properly)

const input = document.querySelector("input");

// you get the same result with these 2
console.log(input.parentElement)

console.log(input.closest("label"))

// you can use all the method of element 
// like style, classList, etc...

input.parentElement.style.outline = "0.2rem solid red";
<label>
  <input type="text" /> <!-- I know only this -->
</label>

First you can get input element, after get parent with function closest():

var inputElement = document.querySelector('input');
var label = inputElement.closest('label');
console.log(label)
<label>
  <input type="text" /> <!-- I know only this -->
</label>

get the element by the input tag and then look for its parent. However, be sure to check for the undefined and multiple query results from the below code snippet.

document.querySelector("input").parentElement
Related