Code Generator | JavaScript

Creating a DOM Node in JavaScript

This code snippet demonstrates how to create a new DOM node in JavaScript using the `createElement` method from the `document` object. It provides a function called `createNode` which takes a tag name as an argument and returns a newly created DOM


Empty image or helper icon

Prompt

create node

Answer

To create a node in JavaScript, you can use the createElement method from the document object. Here is a succinct code snippet to accomplish this:

/**
 * Creates a new DOM node with the specified tag name.
 *
 * @param {string} tagName - The name of the tag for the new node.
 * @returns {Element} - The newly created DOM node.
 */
function createNode(tagName) {
  return document.createElement(tagName);
}

Usage example:

const div = createNode('div');
console.log(div); // <div></div>

In the example above, the createNode function is called with the argument 'div', which creates a new <div> element. The newly created node is then logged to the console.

Unit testing can be done using a testing framework like Jest. Here is an example of a unit test using Jest:

test('createNode creates a new node with the specified tag name', () => {
  const div = createNode('div');
  
  expect(div.tagName.toLowerCase()).toBe('div');
});

In the test above, we create a new div node using the createNode function and assert that its tag name is 'div'.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

This code snippet demonstrates how to create a new DOM node in JavaScript using the createElement method from the document object. It provides a function called createNode which takes a tag name as an argument and returns a newly created DOM node. The usage example shows how to create a <div> element using createNode. Additionally, it mentions how unit testing can be done using a testing framework like Jest, with an example of a unit test for createNode function.