admin管理员组

文章数量:1426008

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?

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?

Share Improve this question asked Sep 13, 2022 at 17:50 user19485937user19485937 3
  • 2 See :has() – Ouroborus Commented Sep 13, 2022 at 18:07
  • @Ouroborus I think this is best than the js solution! thanks, because is native selector – user19485937 Commented Sep 13, 2022 at 18:11
  • 1 @stackdeveloper yes is good solution also this, but isn't supported for now, at least firefox/IE and chrome from the latest versions (105+). try see here caniuse./?search=has , maybe use it in the future when it will be supported. but is better if is work for your target of users – Laaouatni Anas Commented Sep 13, 2022 at 20:07
Add a ment  | 

3 Answers 3

Reset to default 4

use .parentElement or use .closest()

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

if you want only the parent element.

closest: https://developer.mozilla/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

本文标签: htmlcan I query select the Parent from child in JavascriptStack Overflow