search

Home  >  Q&A  >  body text

Fix bug TS2339 - Property method does not exist on 'HTMLElement'

When I press the "Next" button, the code below is triggered, performing the desired action (scrolling to my element if needed).

But I get this error: Error TS2339: Property 'scrollIntoViewIfNeeded' does not exist on type 'HTMLElement'. I cannot build my project.

const h3Title = ref<HTMLElement | null>(null)
function nextStep(
  currentStep.value++;
  
  if (h3Title.value) {
    h3Title.value.scrollIntoViewIfNeeded({behavior: "smooth", block: "start"})
  }

P粉481815897P粉481815897385 days ago699

reply all(1)I'll reply

  • P粉958986070

    P粉9589860702023-12-26 10:50:15

    I think h3Title.value.scrollIntoView({block: "nearest"}) Using the standard scrollIntoView property will achieve what you want (no scrolling if the element is already in view).

    If you really want typescript to recognize the non-standard scrollIntoViewIfNeeded property, you can add it to the HTMLElement interface (or create a new interface that extends HTMLElement):

    // global.d.ts
    interface HTMLElement {
      scrollIntoViewIfNeeded?: any;
    }
    

    Or: Convert h3Title.value to any type

    (h3Title.value as any).scrollIntoViewIfNeeded()
    

    reply
    0
  • Cancelreply