Incorporate innerHTML by appending instead of overwriting

Just a quick question, can we actually add content to a

<div id="whatEverId">hello one</div>
by utilizing:

document.getElementById("whatEverId").innerHTML += " hello two";

Is there a way to INSERT content into the div without replacing it??? So that I could achieve

<div id="whatEverId">hello one hello two</div>

(using something similar, of course)

Answer №1

<div id="random">hey there</div>
<script>
document.getElementById("whatsoever").innerHTML += " hey you";
</script>

Answer №2

It is important to note that when using element.innerHTML += 'content', it will reset input fields and textarea fields to their default empty state, uncheck checkboxes, and remove any events attached to those elements (such as onclick, on hover, etc.). This is because the entire innerHTML is reinterpreted by the browser, causing it to be cleared and then refilled with the combined content.

If you want to preserve the state of the elements, you should create a new element (such as a <span>) and append it to the current element like this:

let newElement = 'span'
newElement.innerHTML = 'new text'
document.getElementById('oldElement').appendChild(newElement)

Answer №3

Changing the content of an element with the id "whatEverId" by adding the string "hello two" to it using JavaScript.

Answer №4

Instead of following jcomeau_ictx's inefficient method for editing innerHTML, a more effective approach is to detach the element, make changes, and then reattach it to the parent node. For further guidance, refer to Ben Cherry's PPT available at

To properly detach elements, utilize Native JavaScript from this gist: https://gist.github.com/cowboy/938767

Answer №5

In case you are appending content, simply replace the equal sign with a plus equals sign.

document.getElementById("whatEverId").innerHTML += 'hello two';

If you are prefixing content:

document.getElementById("whatEverId").innerHTML = 'hello two' + document.getElementById("whatEverId").innerHTML;

I highly recommend using jQuery or MooTools javascript libraries/frameworks for tasks like this. If you need to add tags and not just text nodes, then it is advisable to use the DOM createElement method or one of those libraries/frameworks mentioned above.

Answer №6

To achieve this, simply add a div string as shown below:

Use the following code to append 'Hello Two' inside the element with the id of div_id: document.getElementById('div_id').innerHTML += 'Hello Two';

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with handling keypress event and click event in Internet Explorer

Below is the HTML code for an input text box and a button: <div id="sender" onKeyUp="keypressed(event);"> Your message: <input type="text" name="msg" size="70" id="msg" /> <button onClick="doWork();">Send</button> </di ...

A comprehensive guide on creating translation files using grunt angular-translate from original JSON files containing translations

I have a unique angular application that requires support for multiple languages. To achieve this, I have implemented the angular translate task in the following manner. My goal is to create separate language files which can be loaded later using the useSt ...

Overflow is causing interference with the scrollY value

I've been attempting to retrieve the scrollY value in my React app, but it seems to be affected by overflow-related issues. Below is the code snippet I used to access the scrollY value: import React from "react"; import { useEffect, use ...

What is the best way to structure a hierarchy in an array or object data using Node.js?

I have the following data arrangement: [{ Country: 'USA', State: 'CA', City: 'LA', District: 'LA-1',Town: 'LA-1,LA-1a,LA_AZ_A',Area: 'Area 51'}, { Country: 'USA', State: 'CA&ap ...

What could be causing my jQuery script to malfunction?

After scouring through numerous Stack Overflow questions and conducting countless Google searches, I am still stumped by the issue at hand. As a beginner in web development, all I want is for this simple page to function properly. Can someone please point ...

After running the JavaScript function, the temporary display of textbox is initiated

I am trying to implement a feature where a textbox is shown or hidden when a user clicks on a filter icon in the header of a gridview. Initially, the textbox is hidden but when the icon is clicked, it briefly appears before disappearing again as if the pag ...

Tips for triggering functions when a user closes the browser or tab in Angular 9

I've exhausted all my research efforts in trying to find a solution that actually works. The problem I am facing is getting two methods from two different services to run when the browser or tab is closed. I attempted using the fetch API, which worke ...

Tips for adjusting font size automatically to fit within its parent container every time

On my blog, the post titles are displayed in a div with a video playing in the background. The length of the title varies, ranging from 2 words to over 20 words. When the title is too long, it may overflow from its parent container where the video is playi ...

Using useCallback with an arrow function as a prop argument

I'm having trouble understanding the code snippet below <Signup onClick={() => {}} /> Upon inspecting the Signup component, I noticed the implementation of useCallback as follows const Signup = ({onClick}) => { const handleClick = us ...

Handling JSON Objects with Next.js and TypeScript

Currently, I am working on a personal project using Next.js and Typescript. Within the hello.ts file that is included with the app by default, I have added a JSON file. However, I am facing difficulties in mapping the JSON data and rendering its content. T ...

JavaScript - combining elements of an array of time

I've encountered a challenge where I need to calculate the total time duration from an array that contains time durations like ['00:30', '01:30', '03:00', '04:30']. The code snippet I'm using for this task ...

Smooth Div Scroll experiencing display issues

Trying to integrate the smooth div scroll, specifically the "Clickable Logo Parade" found at: Successfully implemented it on a blank page exactly as desired, but encountering issues when inserting it into the current layout. Could something be causing int ...

AmplifyJS is throwing an error: TypeError - It seems like the property 'state' is undefined and cannot be read

I am currently working on integrating the steps outlined in the Amplify walkthrough with an Angular cli application. My app is a brand new Angular cli project following the mentioned guide. My objective is to utilize the standalone auth components a ...

Issue with Angular translation when utilizing a dynamic key variable

I am currently developing a project with Angular Js and incorporating the Angular-translate module In a specific scenario, I encountered an issue where the translation key needed to be stored as a variable. To address this, I created an object within the ...

The 'xxx' type is lacking various properties compared to the 'xxx[]' type, such as length, pop, push, concat, and many others

Utilizing typescript and reactjs, the issue lies within this component import type { InputProps } from "../utils/types" const Input = (props: InputProps) => { const makeChildren = () => { return ( <> ...

Unable to adjust the x-axis time display in Chart.js

Within my ChartData Component, I am fetching data from an API and displaying it through a chart. The crucial aspect here is the determine Format Logic, which determines the time format of the data. My main challenge lies in changing the time display when s ...

Font size for the PayPal login button

I am looking to adjust the font size of the PayPal Login button in order to make it smaller. However, it appears that the CSS generated by a script at the bottom of the head is overriding my changes. The button itself is created by another script which als ...

Clicking on an anchor tag will open a div and change the background color

.nav_bar { background: #c30015; margin-left: 50px; float: left; } .nav_bar ul { padding: 0; margin: 0; display: flex; border-bottom: thin white solid; } .nav_bar ul li { list-style: none; } .nav_bar ul li a { ...

Discovering a value that aligns with one of the values in an array using Javascript

Just a heads up: this quiz is super simple and only has one input field for each question. This block of Javascript code is used to check if the answer entered in the input field is correct or not. In this case, it checks if the answer entered is 'en ...

A guide on how to efficiently retrieve a string within a function in a native module in a React Native

I'm currently tackling a function related to the native elements of iOS that is coded in Objective-C, My goal is to create a method that will output a string in Objective-C, However, I've hit a roadblock while trying to implement this method: T ...