Javascript element append string

Inserting elements and text-data to the DOM using JavaScript

JavaScript offers various methods for inserting elements and content to a web page.

The type of method to choose when inserting new content into the DOM depends on where it should be inserted and the type of content (an element or text-based data).

Table of contents

At bottom of page or element

append()

The append() method will insert an element or string (or a ‘stringifiable’ value like a number) as the final content in the element it is applied to:

document.body.append("Newly inserted content"); // Inserts text node at end of page const newDiv = document.createElement('div'); newDiv.id = "newDiv"; document.body.append(newDiv); // Inserts div element after previously inserted text node newDiv.append("New text inside div"); // Final text node in div newDiv.append("Even newer text"); // New final text node in div // DOM output: // Newly inserted content // 
// New text inside div // Even newer text //

It is also possible to append multiple elements and text values in one go:

const para = document.createElement('p'); para.textContent = "This is a paragraph element"; const txt = "This is a string"; const num = 123; document.body.append(para, txt, num); // Final page items are para, txt and then num 

appendChild()

appendChild() also inserts new content last, but only accepts HTML elements and will only insert a single element in one use.

Читайте также:  Css label input margin

Note that no error is thrown when trying to insert more than one element – additional content is simply ignored.

const firstPara = document.createElement('p'); firstPara.textContent = "This is a paragraph element"; const nextPara = document.createElement('p'); nextPara.textContent = "This is another paragraph element"; // Correct usage: document.body.appendChild(firstPara); // Usages to avoid: document.body.appendChild(firstPara, nextPara); // firstPara appended, nextPara ignored document.body.appendChild(firstPara, "blah blah blah"); // firstPara appended, string ignored document.body.appendChild("blah blah blah"); // Uncaught TypeError: Failed to execute 'appendChild' on 'Node' 

In general, it is better practice to use appendChild() over append() when you want to insert a single HTML element to the page because it is more likel to catch a content type error.

At top of page or element

prepend()

prepend() is the sister method of append() . It also accepts both elements and text content, as well as multiple in one use.

But with prepend() , content is inserted before any existing content inside the element it is applied to.

const para = document.createElement('p'); para.textContent = "This is a paragraph element"; const txt = "blah blah blah"; document.body.prepend(para, txt); // para and then txt appear before any existing content on page // DOM output: // 

This is a paragraph element

// blah blah blah

In case you were wondering, no prependChild() method exists!

As nth child on page or within element

insertBefore()

The insertBefore() method is ideal for inserting an element between various child elements within a parent element.

insertBefore() is applied to a parent element. It requires two arguments to be passed into it: the new element to insert and the one it should be inserted before.

    //
  • I am the first child //
  • I am the middle child //
  • I’m the last child //
    //
  • I am the first child //
  • I’m the unexpected fourth child //
  • I am the middle child //
  • I’m the last child //

Another way to use insertBefore() is to find the index of an element at a position of interest and specify this index when specifying the element the new one should be inserted before:

  

para1

para2

para3

para4

Note that insertBefore() can only be used to insert a new element to the DOM.

Inserting after a child element

There is no insertAfter() method. But you can adapt insertBefore() to behave this way by using nextSibling when specifying the element to insert the new one after:

Insert next to or inside an element

insertAdjacentHTML()

The insertAdjacentHTML() writes content as HTML nearby or inside an element it is called on.

As a first argument, it accepts one of four string values: ‘beforebegin’ , ‘afterbegin’ , ‘beforeend’ and ‘afterend’ .

The second argument can be any valid HTML to write to the DOM:

insertAdjacentElement()

This method works in the same way as insertAdjacentHTML() except it inserts a HTML element close to or inside the element it is applied to:

const content = document.createElement('article'); content.textContent = "I'm the content inside the div"; const heading = document.createElement('h1'); heading.textContent = "I am the title of the article"; content.insertAdjacentElement('afterbegin', heading); document.body.append(content); // DOM output: // // 

I am the title of the article

// I'm the content inside the div //

insertAdjacentText()

Works in the same way, but accepts a string and writes to the DOM as text:

const content = document.createElement('article'); content.textContent = "I'm the content inside the div"; document.body.append(content); const thanksForReading = "Thanks for reading!"; content.insertAdjacentText('afterend', thanksForReading); // DOM output: // 
I'm the content inside the div
// Thanks for reading!

Источник

Element: append() method

The Element.append() method inserts a set of Node objects or string objects after the last child of the Element . String objects are inserted as equivalent Text nodes.

  • Element.append() allows you to also append string objects, whereas Node.appendChild() only accepts Node objects.
  • Element.append() has no return value, whereas Node.appendChild() returns the appended Node object.
  • Element.append() can append several nodes and strings, whereas Node.appendChild() can only append one node.

Syntax

append(param1) append(param1, param2) append(param1, param2, /* … ,*/ paramN) 

Parameters

A set of Node or string objects to insert.

Return value

Exceptions

Thrown when the node cannot be inserted at the specified point in the hierarchy.

Examples

Appending an element

let div = document.createElement("div"); let p = document.createElement("p"); div.append(p); console.log(div.childNodes); // NodeList [ 

]

Appending text

let div = document.createElement("div"); div.append("Some text"); console.log(div.textContent); // "Some text" 

Appending an element and text

let div = document.createElement("div"); let p = document.createElement("p"); div.append("Some text", p); console.log(div.childNodes); // NodeList [ #text "Some text", 

]

The append method is unscopable

The append() method is not scoped into the with statement. See Symbol.unscopables for more information.

let div = document.createElement("div"); with (div)  append("foo"); > // ReferenceError: append is not defined 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 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.

Источник

How To Append Text To An Element Using JavaScript

append text to an element using JavaScript

In this article, you will learn how to append text to an element using JavaScript by getting the element and adding a string to its .value or .innerHTML attribute or using the .append() function if you’re using JQuery.

Append text to an element using JavaScript

Example of HTML:

Using JavaScript and the .innerHTML and .value attribute

If you don’t know much about JQuery, simply get the desired element and set its .innerHTML or .value attribute.

To get the element, you use either the document.getElementById() or document.getElementsByClassName() function.

Though please note two things:

  • The value attribute only applies to input fields/controls ( , ), otherwise use .innerHTML
  • The .getElementById() function returns a single element with the specified id , while the .getElementsByClassName() returns an HTMLCollection (an array with some quirks) of elements with the same class (or className as defined by JavaScript)

Though to append text, simply add a string using += as the .innerHTML and .value attribute is also a string and works as one.

function append() < const text = document.getElementById("text_id"); text.innerHTML += "LearnShareIT"; >function appendAll() < const texts = document.getElementsByClassName("text"); for (var i = 0 ; i < texts.length ; i++) < var text = texts[i]; text.innerHTML += "LearnShareIT"; >>

Though please note that the .getElementsByClassName() function only returns an HTMLCollection class and not an array, so something like .forEach() or the of keyword does not work.

Using JQuery and the .html() and .val() function

JQuery is a JavaScript library that simplifies many JavaScript features like document traversal, animations, event listening and handling, and attribute manipulation. If you can, learn and use JQuery.

The problem’s solution will be the same as regular JavaScript but is different in syntax and heavily streamlined. For example:

  • To get an element, you use $(id/class/tag) (i.e. a selector) in which an id starts with “#” and class starts with “.”
  • Instead of getting the the text and adding a string, simply use the .append() function, which appends an HTML value to the specified HTML element.

Remember that you need to set up the library before you write the code. Either download it here, or copy the line below into the .

function append() < $("#text_id").append("LearnShareIT"); >function appendAll()

Append Append All function append_jquery() < $(“#text_id_jquery”).append(“LearnShareIT”); >function appendAll_jquery()

Summary

To append text to an element using JavaScript, you need to get the element using the .getElementById() or .getElementsByClassName() function, then add a string to the text using either the .innerHTML or .value attribute. Though if you’re using JQuery, you use the $() and use the .append() function to add text.

Maybe you are interested:

Hello, my name is Davis Cole. I love learning and sharing knowledge about programming languages. Some of my strengths are Java, HTML, CSS, JavaScript, C#,… I believe my articles about them will help you a lot.

Programming Languages: Java, HTML, CSS, JavaScript, C#, ASP.NET, SQL, PHP

Источник

Оцените статью