In Node.js, document.getElementById() will throw an error like ReferenceError: document is not defined because Node.js does not have a built-in DOM (Document Object Model) like browsers do. The document object is part of the browser environment, but Node.js runs on the server and doesn’t have access to the browser’s DOM.
To work with the DOM in Node.js, you can use libraries that simulate a browser environment. One of the most popular libraries for this is jsdom.
You can install the jsdom package via npm (Node Package Manager). It provides an implementation of the web standards (like the document object) in a Node.js environment.
Run the following command to install jsdom:
npm install jsdom
Here’s how you can use jsdom to create a document object in Node.js:
const { JSDOM } = require('jsdom');
// Create a new DOM with an HTML string or an empty document
const dom = new JSDOM(`<html><body><div id="my-element">Hello, World!</div></body></html>`);
// Access the document object from the JSDOM instance
const document = dom.window.document;
// Now you can use document.getElementById
const element = document.getElementById('my-element');
console.log(element.textContent); // Outputs: Hello, World!
Here’s a complete example of using jsdom to access and manipulate HTML elements:
const { JSDOM } = require('jsdom');
// HTML content to simulate the document
const htmlContent = `
<html>
<body>
<div id="my-element">Hello, World!</div>
<p id="my-paragraph">This is a paragraph.</p>
</body>
</html>
`;
// Create a new DOM from the HTML string
const dom = new JSDOM(htmlContent);
// Access the document object
const document = dom.window.document;
// Select the element with id "my-element"
const element = document.getElementById('my-element');
console.log(element.textContent); // Outputs: Hello, World!
// Select the paragraph with id "my-paragraph"
const paragraph = document.getElementById('my-paragraph');
console.log(paragraph.textContent); // Outputs: This is a paragraph.
Work with our skilled Node developers to accelerate your project and boost its performance.
Hire Node.js Developers