skip to Main Content

I have custom element which has an input element that is not a first grade child. I want to get the parent custom element from the input and I tried using input.closest() but it does not work with custom elements tag names

const card = input.closest("game-card");

I need to get the first parent that is a game card so is there a way to do this with custom elements?

2

Answers


  1. let inputEl = document.querySelector('#test');
    console.log(inputEl)
    console.log(inputEl.closest('game-card'));
    <game-card>
      <first-level>
        <second-level>
          <input id="test" />
        </second-level>
      </first-level>
    </game-card>
    Running this will log to console, the closest game-card
    Login or Signup to reply.
  2. the closest method parameter would be :
    use ‘#game-card’, if custom parent element have id=’game-card’
    or
    use ‘.game-card’, if custom parent element have class=’game-card’.

    your problem will be resolved.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search