Search code examples
javascripthtmljquery-selectors

can I query select the Parent from child in Javascript?


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?


Solution

  • 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>