Search code examples
typescriptjsdom

Can't find a working syntax for jsdom.getElementById in typescript


Using the following code snippet I've tried a variety of search strings like the following list but so far getElementById() always returns undefined. What am I doing wrong? '//h1' 'h1' 'title' '//title' 'body' 'Hello' etc

Output from the following code is always elem=null

import { JSDOM } from 'jsdom';
const htmlContent = `<!DOCTYPE html><html lang="en">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Hello World Title</title>
</head>
<body>
    <h1>Hello World Body</h1>
</body>
</html>`;
// verify the starting text is OK
console.log(`htmlContent=${htmlContent.substring(50, 200)}`);

const dom = new JSDOM(htmlContent);
const doc = dom.window.document;
const elem = doc.getElementById("//title");
console.log(`      elem=${elem}`);

Solution

  • You are using doc.getElementById to get the value from tag <title>. This is incorrect as <title> is a tag in the DOM. You should use getElementsByTagName("title");

    const elem = doc.getElementsByTagName("//title")[0];
    

    Alternatively assign an id to your <title>. For example, <title id="title1">Hello World Title</title>. Then you should able to get the value with const elem = doc.getElementById("//title1");