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}`);
1
You need to put an ID to the element if you want to getElementById.
you are using doc.getElementById to get the value from tag . this is incorrect as is a tag in dom .
you should use getElementsByTagName(“title”);
const elem = doc.getElementsByTagName(“//title”)[0];
alternatively assign an id to your
example Hello World Title
then you should able to get the value with const elem = doc.getElementById(“//title1”);