Javascript add element with class

How to create a new element with class name in JavaScript

JavaScript provides a native way to create new elements. A single createElement() method is available inside the document object which is supported by all browsers. But it’s not enough to create a new element with a class name or any other attributes for that matter.

Creating an element

The createElement() method accepts two arguments, first one is being the HTML tag of the new element.

const anchorElement = document.createElement('a') 

It is relatively easy to use. However, this method creates an empty element (without any content) and without any attributes. So additional steps must be taken if you wish to create a more meaningful element.

Adding content to the new element

To add content to your element you can choose one of four ways, depending on your needs. It can be:

  1. innerHTML — to set HTML to the element;
  2. innerText — to set the text of the element;
  3. textContent — to set text node to the element;
  4. appendChild() — to append HTML elements or Nodes to the element.

In our case let’s use innerText property for the sake of example:

anchorElement.innerText = 'Apply Now' 

Adding custom class name and attributes

So when the content is added let’s add missing attributes with setAttribute() method:

anchorElement.setAttribute('href', 'https://example.com/apply-now') 

To add a class name to your element you can use the classList property with the add method:

anchorElement.classList.add('apply-now-link') 

Finally to add created element to the DOM, use the appendChild() method:

document.body.appendChild(anchorElement) 

The final code snippet looks as follows:

const anchorElement = document.createElement('a') anchorElement.innerText = 'Apply Now' anchorElement.setAttribute('href', 'https://example.com/apply-now') anchorElement.classList.add('apply-now-link') document.body.appendChild(anchorElement) 

Creating custom function

The example given above is quite simple. But imagine creating multiple different elements dynamically that could contain different attributes.

For that, you can create your own custom helper function that will create a new element and set attributes.

function createCustomElement (tag, content, attributes)  const element = document.createElement(tag) element.innerHTML = content for (const name in attributes)  element.setAttribute(name, attributes[name]) > return element > 

Let’s break it down. The function accepts three arguments.

First, it creates a new element from the tag argument which should be a string.

Next, it sets the content via innerHTML property for more versatility (you can pass both text and HTML strings).

Then, it iterates over the attributes argument (should be an object), and sets corresponding HTML attributes with values.

Finally, the function returns a new element.

Compose necessary arguments and then use the function as follows:

const tag = 'a' const content = 'Apply Now' const elementAttributes =  href: 'https://example.com', class: 'link', target: '_blank', rel: 'noopener noreferrer' > const newAnchor = createCustomElement(tag, content, elementAttributes) document.body.appendChild(newAnchor) 

Now you can re-use this function in different places to create your own ready-to-go elements with content and attributes.

function createCustomElement (tag, content, attributes)  const element = document.createElement(tag) element.innerHTML = content for (const name in attributes)  element.setAttribute(name, attributes[name]) > return element > const tag = 'a' const content = 'Apply Now' const elementAttributes =  href: 'https://example.com', class: 'link', target: '_blank', rel: 'noopener noreferrer' > const newAnchor = createCustomElement(tag, content, elementAttributes) document.body.appendChild(newAnchor) 

Update

As noted by @Jhey, you can create a new element with all the attributes using the Object.assign method.

This approach is much cleaner:

const newAnchor = Object.assign( document.createElement('a'),  innerText: 'Apply Now', href: 'https://example.com', className: 'link', target: '_blank', rel: 'noopener noreferrer' > ) document.body.appendChild(newAnchor) 

Источник

Learn How JavaScript Create Element

In this tutorial, you will learn how JavaScript create element with classes and id. You will see how to append these newly created elements at the desired location on the webpage.

One of the most commonly used tasks in web development is to create elements dynamically . This is done by using JavaScript to make websites interactive to the users.

A simple example you can see in a to do list app where you can add, delete and edit to do list items. These list items are created dynamically using JavaScript.

A webpage is interactive when the user is actively engaged with the contents, elements, and functionality of the webpage.

javascript create element

Let’s see how you can create an HTML element using javascript and append it anywhere within the webpage.

Table of content — JavaScript Create Element

Create Element JavaScript

To create an HTML element using JavaScript use the document.createElement() method.

To create an element you need to pass the element name as an argument to the method.

The document.createElement() method creates the element with the given name and returns it as a Node object.

document.createElement("TagName");

The TagName argument is the name of the element you want to create.

  • To create a element pass div , DIV , Div , DiV , etc.
  • To create a

    element pass p or P .

  • To create a element pass img , IMG , Img , IMg , etc.

Note : The createElement method converts the element name to lowercase and then creates the element. So if you pass DIV as an argument, it will create a div element.

The method also returns the reference to the newly created element which you can store to be used later.

let element = document.createElement("P");

Now your element is created and the reference of the element is stored in a variable.

But, this newly created element is floating aimlessly in the document, you have to stitch it to somewhere in the body to be seen or used.

append element in javascript

Append Newly Created Element

Just creating an element is not enough to show it on the webpage. You have to append it to somewhere in the body.

The newly created element has no role in the document and is not visible to the user because it is not part of the DOM yet.

There are 3 methods to append an element to the webpage:

1. append() Method

The append() method appends the element to the end of the parent element.

The method is called upon the parent element and takes the child element as an argument and appends it as the last child of the parent element.

For example in the given example, the is parent element and the

is the child element. If you add another

element, it will be appended as the last child of the element.

let element = document.createElement("P"); element.innerHTML = "Paragraph 3"; // Append the element to the parent element document.getElementById("parent").append(element);

The final look of the DOM after the above code is:

Paragraph 1

Paragraph 2

Paragraph 3

2. appendChild() Method

The appendChild() method is the same as the append() method it appends the element to the end of the parent element.

Although there are few differences between the append() and appendChild() methods:

append() appendChild()
Using the append() method you can append both DOMString and DOMNodes (element) to the parent element. Using the appendChild() method you can append only DOMNodes (element) to the parent element.
The append() method returns the appended node. The appendChild() method returns nothing.
The append() method can append multiple elements at once. The appendChild() method can only append one element at a time.

Here is an example using the appendChild() method:

// selecting parent element var parent = document.getElementById('parent'); var child = document.createElement('p'); child.innerHTML = 'Paragraph 3'; parent.appendChild(child);

3. insertBefore() Method

The insertBefore() method inserts the element before the reference element and makes it the previous sibling of the reference element.

The method is called upon the parent element and operations of inserting the element are performed on its child nodes.

If the node already exists in the parent element, it will be moved to the new position.

// selecting parent var parent = document.getElementById('parent'); // selecting sibling element var sibling = document.getElementById('para1'); var element = document.createElement('p'); element.innerHTML = 'Paragraph 3'; parent.insertBefore(element, sibling);

Here is how DOM looks before and after appending a new element.

append element to parent element

Javascript Create Element with Class

To create an element with a class, you need to add the class attribute to the element after creating it.

To add a class to an element, you can use the classList.add() method on the element.

Learn more ways of how Javascript add class to an element.

var parentElement = document.body; // creating new element var element = document.createElement("P"); element.innerHTML = "New paragraph with 'box' class."; // adding class to the element element.classList.add("box"); parentElement.appendChild(element);

Javascript Create element with id

The id property of an element is used to get and set the id of an element.

To create an element with an id use createElement to create an element and assign an id to element.id .

In the example below whenever the button is clicked it create an element and add a unique id to it.

 

Javascript Create element with attributes

HTML elements can have attributes. Attributes are used to add extra information to an element.

To add an attribute to an element, you can use the setAttribute() method on the element.

Elements like and have some compulsory attributes like type and src .

To add an attribute to an element, use the setAttribute() method on the element and pass the attribute name and value as arguments.

Here is an example that creates an image element and adds a few attributes to it.

let parentElement = document.body; // creating new element let element = document.createElement("IMG"); // adding attributes to the element element.setAttribute("src", "https://i.imgur.com/Rnj7kZj.jpeg"); element.setAttribute("alt", "picture of pluto"); element.setAttribute("title", "picture of pluto"); parentElement.appendChild(element);

Conclusion

You have seen how Javascript create element. Here is a quick summary:

  1. Create element using document.createElement() method.
  2. Add class to an element using element.classList.add() method.
  3. Add id to an element using element.id = «id» + count; .
  4. Add attribute to an element using element.setAttribute() method.
  5. Append element to parent element using append() , appendChild() , or insertBefore() method.

Источник

Читайте также:  Таблицы
Оцените статью