Javascript document createelement div style

JavaScript CreateElement

Summary: in this tutorial, you will learn how to use the JavaScript document.createElement() to create a new HTML element and attach it to the DOM tree.

To create an HTML element, you use the document.createElement() method:

let element = document.createElement(htmlTag);Code language: JavaScript (javascript)

The document.createElement() accepts an HTML tag name and returns a new Node with the Element type.

1) Creating a new div example

Suppose that you have the following HTML document:

html> html> head> meta charset="utf-8"> title>JS CreateElement Demo title> head> body> body> html>Code language: HTML, XML (xml)

The following example uses the document.createElement() to create a new element:

let div = document.createElement('div');Code language: JavaScript (javascript)

And add an HTML snippet to the div :

div.innerHTML = 'p>CreateElement example p>';Code language: HTML, XML (xml)

To attach the div to the document, you use the appendChild() method:

document.body.appendChild(div);Code language: CSS (css)
html> html> head> meta charset="utf-8"> title>JS CreateElement Demo title> head> body> script> let div = document.createElement('div'); div.id = 'content'; div.innerHTML = '

CreateElement example

'
; document.body.appendChild(div);
script> body> html>
Code language: HTML, XML (xml)

Adding an id to the div

If you want to add an id to a div , you set the id attribute of the element to a value, like this:

let div = document.createElement('div'); div.id = 'content'; div.innerHTML = '

CreateElement example

'
; document.body.appendChild(div);
Code language: JavaScript (javascript)

Adding a class to the div

The following example set the CSS class of a new div note :

let div = document.createElement('div'); div.id = 'content'; div.className = 'note'; div.innerHTML = '

CreateElement example

'
; document.body.appendChild(div);
Code language: JavaScript (javascript)

Adding text to a div

To add a piece of text to a , you can use the innerHTML property as the above example, or create a new Text node and append it to the div :

// create a new div and set its attributes let div = document.createElement('div'); div.id = 'content'; div.className = 'note'; // create a new text node and add it to the div let text = document.createTextNode('CreateElement example'); div.appendChild(text); // add div to the document document.body.appendChild(div);Code language: JavaScript (javascript)

Adding an element to a div

To add an element to a div , you create an element and append it to the div using the appendChild() method:

let div = document.createElement('div'); div.id = 'content'; div.className = 'note'; // create a new heading and add it to the div let h2 = document.createElement('h2'); h2.textContent = 'Add h2 element to the div'; div.appendChild(h2); // add div to the document document.body.appendChild(div); Code language: JavaScript (javascript)

2) Creating new list items ( li ) example

Let’s say you have a list of items:

ul id="menu"> li>Home li> ul> Code language: HTML, XML (xml)

The following code adds two li elements to the ul :

let li = document.createElement('li'); li.textContent = 'Products'; menu.appendChild(li); li = document.createElement('li'); li.textContent = 'About Us'; // select the ul menu element const menu = document.querySelector('#menu'); menu.appendChild(li); Code language: JavaScript (javascript)
ul id="menu"> li>Home li> li>Products li> li>About Us li> ul>Code language: HTML, XML (xml)

3) Creating a script element example

Sometimes, you may want to load a JavaScript file dynamically. To do this, you can use the document.createElement() to create the script element and add it to the document.

The following example illustrates how to create a new script element and loads the /lib.js file to the document:

let script = document.createElement('script'); script.src = '/lib.js'; document.body.appendChild(script);Code language: JavaScript (javascript)

You can first create a new helper function that loads a JavaScript file from an URL:

function loadJS(url) < let script = document.createElement('script'); script.src = url; document.body.appendChild(script); >Code language: JavaScript (javascript)

And then use the helper function to load the /lib.js file:

loadJS('/lib.js');Code language: JavaScript (javascript)

To load a JavaScript file asynchronously, you set the async attribute of the script element to true :

function loadJSAsync(url) < let script = document.createElement('script'); script.src = url; script.async = true; document.body.appendChild(script); >Code language: JavaScript (javascript)

Summary

  • The document.createElement() creates a new HTML element.
  • The element.appendChild() appends an HTML element to an existing element.

Источник

Javascript document createelement div style

If I load the page from the example above, I can see that the attributes are applied to the element.

attributes applied successfully

# Create an Element with Style attribute using JavaScript

To create an element with a style attribute:

  1. Use the document.createElement() method to create the element.
  2. Use the setAttribute() method to set the style attribute on the element.
  3. Add the element to the page using the appendChild() method.

Here is the HTML for the example.

Copied!
DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> div id="box">div> script src="index.js"> script> body> html>

And here is the related JavaScript code.

Copied!
// ✅ Create element const el = document.createElement('div'); // ✅ Set Style Attributes on Element el.setAttribute( 'style', 'background-color: salmon; color: white; width: 150px; height: 150px;', ); // ✅ Alternatively, Set styles on Element // el.style.backgroundColor = 'salmon'; // el.style.color = 'white'; // el.style.width = '150px'; // el.style.height = '150px'; // ✅ Add text content to the element el.textContent = 'Hello world'; // ✅ Or set the innerHTML of the element // el.innerHTML = `Hello world`; // ✅ add element to DOM const box = document.getElementById('box'); box.appendChild(el);

We used the document.createElement method to create the element.

The only parameter we passed to the method is the type of element to be created ( div in the example).

The createElement method returns the newly created element.

We used the setAttribute method to set the style attribute on the element.

The setAttribute method takes 2 parameters:

  1. name — the name of the attribute whose value is to be set.
  2. value — the value to assign to the attribute.

If the attribute already exists, the value is updated, otherwise, a new attribute is added with the specified name and value.

Alternatively, you can use the style object to set styles on the element.

Copied!
const el = document.createElement('div'); el.style.backgroundColor = 'salmon'; el.style.color = 'white'; el.style.width = '150px'; el.style.height = '150px';

When setting styles using the style property, multi-name words are camel-cased.

You can use the textContent property to set the element’s text content or the innerHTML property to set the element’s inner HTML markup.

You shouldn’t use the innerHTML property with user-provided data without escaping it. This would leave your application open to cross-site scripting attacks.

You can use the appendChild method to add the element to the page.

The method adds a node to the end of the list of children of the element it was called on.

If I load the page from the example, I can see that the style attribute is successfully set on the element.

style attribute successfully set

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Document: createElement() method

In an HTML document, the document.createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn’t recognized.

Syntax

createElement(tagName) createElement(tagName, options) 

Parameters

A string that specifies the type of element to be created. The nodeName of the created element is initialized with the value of tagName. Don’t use qualified names (like «html:a») with this method. When called on an HTML document, createElement() converts tagName to lower case before creating the element. In Firefox, Opera, and Chrome, createElement(null) works like createElement(«null») .

An object with the following properties:

The tag name of a custom element previously defined via customElements.define() . See Web component example for more details.

Return value

Note: A new HTMLElement is returned if the document is an HTMLDocument, which is the most common case. Otherwise a new Element is returned.

Examples

Basic example

This creates a new and inserts it before the element with the ID » div1 «.

HTML

doctype html> html lang="en-US"> head> meta charset="UTF-8" /> title>Working with elementstitle> head> body> div id="div1">The text above has been created dynamically.div> body> html> 

JavaScript

.body.onload = addElement; function addElement()  // create a new div element const newDiv = document.createElement("div"); // and give it some content const newContent = document.createTextNode("Hi there and greetings!"); // add the text node to the newly created div newDiv.appendChild(newContent); // add the newly created element and its content into the DOM const currentDiv = document.getElementById("div1"); document.body.insertBefore(newDiv, currentDiv); > 

Result

Web component example

The following example snippet is taken from our expanding-list-web-component example (see it live also). In this case, our custom element extends the HTMLUListElement , which represents the element.

// Create a class for the element class ExpandingList extends HTMLUListElement  constructor()  // Always call super first in constructor super(); // constructor definition left out for brevity // … > > // Define the new element customElements.define("expanding-list", ExpandingList,  extends: "ul" >); 

If we wanted to create an instance of this element programmatically, we’d use a call along the following lines:

let expandingList = document.createElement("ul",  is: "expanding-list" >); 

The new element will be given an is attribute whose value is the custom element’s tag name.

Note: For backwards compatibility with previous versions of the Custom Elements specification, some browsers will allow you to pass a string here instead of an object, where the string’s value is the custom element’s tag name.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

  • Node.removeChild()
  • Node.replaceChild()
  • Node.appendChild()
  • Node.insertBefore()
  • Node.hasChildNodes()
  • document.createElementNS() — to explicitly specify the namespace URI for the element.

Found a content problem with this page?

This page was last modified on Jul 7, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Create Div Element in JavaScript

Create Div Element in JavaScript

  1. Use the document.createElement() Method in JavaScript
  2. Use document.body.innerHTML to Change Property in JavaScript

We frequently need to dynamically build and customize div elements in our web app. We’ll use JavaScript to construct and customize a div in this tutorial.

Use the document.createElement() Method in JavaScript

Using the document.createElement, we may create an HTML element. createElement is a technique for creating elements.

We supply the tag name of the element we wish to build as a string to use it.

const div = document.createElement("div"); div.style.width = "60px"; div.style.height = "20px"; div.style.background = "green"; div.style.color = "white"; div.innerHTML = "Upwork";  document.body.appendChild(div); 

Using document.createElement Method

Style it and attach it to the body element as a child to make a div. The element object is returned by createElement. The style property’s properties can then be set to apply various styles.

In the style property, all CSS properties are in the camel case. The HTML element’s content is set via innerHTML .

Use document.body.innerHTML to Change Property in JavaScript

We can also change the document’s innerHTML property. To add content to the body element, convert the body to a string with HTML code.

const div = '
Upwork
'
;
document.body.innerHTML = div;

Using document.body.innerHTML to change property

The document.createElement is a technique for creating elements. using it, we can make a div. Then we can style it by setting values for the style property’s properties.

Shiv is a self-driven and passionate Machine learning Learner who is innovative in application design, development, testing, and deployment and provides program requirements into sustainable advanced technical solutions through JavaScript, Python, and other programs for continuous improvement of AI technologies.

Related Article — JavaScript Element

Источник

Читайте также:  Site url in javascript
Оцените статью