Search code examples
javascriptjsdom

elem.text is not a function in JSDOM


import jsdom from 'jsdom'

const virtualConsole = jsdom.createVirtualConsole()

virtualConsole.on('jsdomError', ({stack, detail}) => console.error(stack, detail))

global.document = jsdom.jsdom(`
  <html>
    <body>
      <div id="foo">some text</div>
    </body>
  </html>
`, { virtualConsole })

global.window = document.defaultView
global.navigator = window.navigator

const elem = document.getElementById('foo')
console.log('foo text', elem.text())

This gives me the wonderful error elem.text is not a function

I'm using JSDOM v9.1.0

What am I missing?


Solution

  • .text() is a jQuery method that returns the text content of a given element(s). It isn't actually part of the JavaScript DOM API I'm afraid. Try using the .textContent property. (MDN link).

    const elem = document.getElementById('foo')
    console.log('foo text', elem.textContent)