Table of Contents
2. Append the Element to the DOM
Example: Append to the body
Example: Append to a specific container
3. Set Attributes and Classes (Optional but Common)
4. Complete Example: Create and Append a List Item
Bonus: Inserting Before or at a Specific Position
Key Takeaways
Home Web Front-end JS Tutorial How to create and append elements in JS?

How to create and append elements in JS?

Jul 25, 2025 am 03:56 AM

<p>Use document.createElement() to create a new element; 2. Customize the element through textContent, classList, setAttribute and other methods; 3. Use appendChild() or more flexible append() methods to add elements to the DOM; 4. Optionally use insertBefore(), before() and other methods to control the insertion position; the complete process is to create → custom → add, and you can dynamically update the page content.

<p>How to create and append elements in JS?

<p> Creating and appending elements in JavaScript is a common task when building dynamic web pages. Here's how to do it step by step, with clear and practical examples.

How to create and append elements in JS?

1. Create a New Element with document.createElement()

<p> To create a new HTML element, use document.createElement('tagname') .

 const newParagraph = document.createElement(&#39;p&#39;);
<p> Now you have a <p> element in memory — but it's not yet part of the page.

How to create and append elements in JS?<p> You can set properties like text, attributes, or styles:

 newParagraph.textContent = &#39;This is a new paragraph.&#39;;
// Or use innerHTML if you need to include HTML tags
// newParagraph.innerHTML = &#39;<strong>Bold text</strong>&#39;;

2. Append the Element to the DOM

<p> Use methods like appendChild() or append() to add the element to an existing parent in the DOM.

How to create and append elements in JS?

Example: Append to the body

 document.body.appendChild(newParagraph);

Example: Append to a specific container

 const container = document.getElementById(&#39;container&#39;);
container.appendChild(newParagraph);
<p> ? appendChild() only accepts nodes and adds one at a time.
? append() is more flexible — it can add multiple nodes and even strings.

 container.append(newParagraph); // works the same here
<p> You can also append multiple items:

 const span = document.createElement(&#39;span&#39;);
span.textContent = &#39;A new span&#39;;

container.append(newParagraph, span); // append both

3. Set Attributes and Classes (Optional but Common)

<p> Before appending, you might want to add classes or attributes:

 newParagraph.classList.add(&#39;highlight&#39;);
newParagraph.setAttribute(&#39;id&#39;, &#39;intro-text&#39;);
// Or set styles directly
newParagraph.style.color = &#39;blue&#39;;

4. Complete Example: Create and Append a List Item

 // Step 1: Create elements
const li = document.createElement(&#39;li&#39;);
const strong = document.createElement(&#39;strong&#39;);

// Step 2: Add content
strong.textContent = &#39;Important item&#39;;
li.appendChild(strong);

// Step 3: Add to the list
const ul = document.querySelector(&#39;ul&#39;);
ul.append(li);
<p> This would add <li><strong>Important item</strong></li> to your unordered list.


Bonus: Inserting Before or at a Specific Position

<p> Use insertBefore() or before() / after() for more control.

 const firstItem = ul.children[0];
ul.insertBefore(li, firstItem); // insert new li before the first item
<p> Or use before() to insert before a specific element:

 firstItem.before(li);

Key Takeaways

  • Use document.createElement() to make a new element.
  • Modify it (text, class, attributes) before or after creation.
  • Use appendChild() or append() to add it to the DOM.
  • append() is more modern and flexible; appendChild() is older but widely supported.
<p> Basically, create → customize → append. That's the flow.

The above is the detailed content of How to create and append elements in JS?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1596
276
Micro Frontends Architecture: A Practical Implementation Guide Micro Frontends Architecture: A Practical Implementation Guide Aug 02, 2025 am 08:01 AM

Microfrontendssolvescalingchallengesinlargeteamsbyenablingindependentdevelopmentanddeployment.1)Chooseanintegrationstrategy:useModuleFederationinWebpack5forruntimeloadingandtrueindependence,build-timeintegrationforsimplesetups,oriframes/webcomponents

Advanced Conditional Types in TypeScript Advanced Conditional Types in TypeScript Aug 04, 2025 am 06:32 AM

TypeScript's advanced condition types implement logical judgment between types through TextendsU?X:Y syntax. Its core capabilities are reflected in the distributed condition types, infer type inference and the construction of complex type tools. 1. The conditional type is distributed in the bare type parameters and can automatically split the joint type, such as ToArray to obtain string[]|number[]. 2. Use distribution to build filtering and extraction tools: Exclude excludes types through TextendsU?never:T, Extract extracts commonalities through TextendsU?T:Never, and NonNullable filters null/undefined. 3

What are the differences between var, let, and const in JavaScript? What are the differences between var, let, and const in JavaScript? Aug 02, 2025 pm 01:30 PM

varisfunction-scoped,canbereassigned,hoistedwithundefined,andattachedtotheglobalwindowobject;2.letandconstareblock-scoped,withletallowingreassignmentandconstnotallowingit,thoughconstobjectscanhavemutableproperties;3.letandconstarehoistedbutnotinitial

What is optional chaining (?.) in JS? What is optional chaining (?.) in JS? Aug 01, 2025 am 06:18 AM

Optionalchaining(?.)inJavaScriptsafelyaccessesnestedpropertiesbyreturningundefinedifanypartofthechainisnullorundefined,preventingruntimeerrors.1.Itallowssafeaccesstodeeplynestedobjectproperties,suchasuser.profile?.settings?.theme.2.Itenablescallingme

Generate Solved Double Chocolate Puzzles: A Guide to Data Structures and Algorithms Generate Solved Double Chocolate Puzzles: A Guide to Data Structures and Algorithms Aug 05, 2025 am 08:30 AM

This article explores in-depth how to automatically generate solveable puzzles for the Double-Choco puzzle game. We will introduce an efficient data structure - a cell object based on a 2D grid that contains boundary information, color, and state. On this basis, we will elaborate on a recursive block recognition algorithm (similar to depth-first search) and how to integrate it into the iterative puzzle generation process to ensure that the generated puzzles meet the rules of the game and are solveable. The article will provide sample code and discuss key considerations and optimization strategies in the generation process.

How can you remove a CSS class from a DOM element using JavaScript? How can you remove a CSS class from a DOM element using JavaScript? Aug 05, 2025 pm 12:51 PM

The most common and recommended method for removing CSS classes from DOM elements using JavaScript is through the remove() method of the classList property. 1. Use element.classList.remove('className') to safely delete a single or multiple classes, and no error will be reported even if the class does not exist; 2. The alternative method is to directly operate the className property and remove the class by string replacement, but it is easy to cause problems due to inaccurate regular matching or improper space processing, so it is not recommended; 3. You can first judge whether the class exists and then delete it through element.classList.contains(), but it is usually not necessary; 4.classList

What is the class syntax in JavaScript and how does it relate to prototypes? What is the class syntax in JavaScript and how does it relate to prototypes? Aug 03, 2025 pm 04:11 PM

JavaScript's class syntax is syntactic sugar inherited by prototypes. 1. The class defined by class is essentially a function and methods are added to the prototype; 2. The instances look up methods through the prototype chain; 3. The static method belongs to the class itself; 4. Extends inherits through the prototype chain, and the underlying layer still uses the prototype mechanism. Class has not changed the essence of JavaScript prototype inheritance.

Building a Design System with Storybook and React Building a Design System with Storybook and React Jul 30, 2025 am 05:05 AM

First, use npxstorybookinit to install and configure Storybook in the React project, run npmrunstorybook to start the local development server; 2. Organize component file structure according to functions or types, and create corresponding .stories.js files to define different states in each component directory; 3. Use Storybook's Args and Controls systems to achieve dynamic attribute adjustments to facilitate testing of various interactive states; 4. Use MDX files to write rich text documents containing design specifications, accessibility instructions, etc., and support MDX loading through configuration; 5. Define the design token through theme.js and use preview.js

See all articles