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](https://fs.enterprisedna.co/library/data-mentor/cover-images/PnSOcpEeb3sCNl94C7l12PPtS3MLR0xdaX4m11Zx.webp)
This Query related with thread "JavaScript Deep Dive: Dependency Resolution, Code Snippets, and Optimi"
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'
.
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.