Add a pair of assorted div elements to a shared container

I have two different sections with classes named "red" and "blue". By default, these sections are hidden. I want to duplicate them and display them in a single container named "cont". The red button appends the red section and the blue button appends the blue section.

function createRedSection(word){
  var redSection = document.getElementsByClassName('red')[redPos];
  redPos++;
  var redClone = redSection.cloneNode(true);
  document.getElementById('cont').appendChild(redClone);
  item.style.display = 'inline';
  item.innerHTML = word;
}

function createBlueSection(word){
 //same as red
}

Currently, the red sections appear separately from the blue ones regardless of the order in which they were clicked.

red1|red2|red3|blue1|blue2

How can I make sure that the sections display in the order I clicked them? Whether they are red or blue.

red1|blue1|red2|blue2|blue3

One solution I thought of was to use a common class name and then add the red/blue classes later.

function createRedSection(word){
  var item = document.getElementsByClassName('input-item')[itemPos];
  itemPos++;
  var itemClone = item.cloneNode(true);
  itemClone.className += " red";
  document.getElementById('cont').appendChild(itemClone);
  item.style.display = 'inline';
  item.innerHTML = word;

}

However, this approach did not yield the expected results. The CSS styling got mixed up.

Answer №1

If you're seeking a JavaScript solution only:

HTML :

<div class="red input">red</div>
  <div class="blue input">blue</div>
<div id="cont">
</div>

<button onclick="redCreator('red');">RED</button>

<button onclick="blueCreator('blue');">blue</button>

CSS

.input {
  display: none;
  padding:10px;
 }
.red {
  background:red;
}
.blue {
  background:blue;
}

JS:

function redCreator(word){
  var red =document.getElementsByClassName('red')[0];
  console.log(red);
  var redClone = red.cloneNode(true);
  document.getElementById('cont').appendChild(redClone);
  redClone.style.display = 'inline-block';
  redClone.innerHTML=word;
}

function blueCreator(word){
 var blue =document.getElementsByClassName('blue')[0];
  var blueClone = blue.cloneNode(true);
  document.getElementById('cont').appendChild(blueClone);
  blueClone.style.display = 'inline-block';
  blueClone.innerHTML=word;
}

Add some numbering lines for clarity and ease of use. Keep coding!

Answer №2

After utilizing jQuery (the version utilized in the fiddle is 1.9.1, but it should be compatible with newer versions), I have created a fiddle:

https://jsfiddle.net/27oa1pb7/

In this scenario, hidden div contents are extracted and added to the "cont" container in the order they are clicked. By modifying CSS rules, you have the flexibility to adjust the appearance of the divs. The implementation involves a simple series of jQuery functions:

...
$("#reddiv").clone().show().appendTo( "#cont" )
...

The provided code is based on your requirements as there wasn't a specific HTML or CSS example available.

I trust this explanation proves helpful! Enjoy your coding session!

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

Ways to pass a message from index.html to a Vue.js 3 instance

Picture this scenario: You have a Vue index.html file that also loads a custom script: <!DOCTYPE html> <html lang="en"> <head> ... ... <script type="text/javascript"> languagePluginLoader.then(fun ...

While executing a router.post command, it attempts to retrieve assets from an incorrect directory

Update: I need some clarification, as it is functioning correctly on other pages. The issue lies with my Router.get searching for assets in an incorrect folder and I am struggling to rectify it. All my other GET requests are working fine, but this one spe ...

What is the process of importing an IIFE-based JavaScript module into an Angular TypeScript application?

I have come across a third-party SDK that is structured as an oldschool IIFE based module. The code looks something like this: var ThirdPartySDK = (function() { var export = {}; // Adding some methods to export return export; })(); To use this SD ...

creating an identical copy of a dynamic element's size

I am currently working on a project using react js where I need to incorporate multiple images. My goal is to have standard background divs / rectangles that match the exact size of each image, allowing for animations to be performed on top of them. The sn ...

What is the process for refreshing the component content in Angular 2?

There was a moment during execution when my URL had the following appearance: http://localhost:4200/personal/51c50594-a95c-4a18-ac7b-b0521d67af96 I desire to visit a page with a different GUID and different content. http://localhost:4200/personal/{other ...

"Executing a query on Angular Firestore using the where clause fetches all documents from the

I am encountering a perplexing issue with my angular app that is connected to Firestore. Despite following the documentation closely, when I query for documents in a collection based on a specific condition, the array returned contains every single documen ...

Is there a way to retrieve the id attribute of an option element from the source component?

When a user makes a selection, I am trying to access the id attribute of the HTMLOptionElement. However, it always returns 0 instead of the actual id I passed (such as 1 or 2) from the select tag: <div class="col-8"> <select (cha ...

What action is triggered on an Apple iPhone when a notification is tapped?

Currently, I am working on a React application and testing it on an Apple mobile phone. One issue I encountered is that when I receive an SMS, the number appears as a suggestion above the keyboard. I want to be able to tap on this number and have it automa ...

JQuery content displaying only on the first instance

<script> $(document).ready(function () { $('nav>li').hide(); $('ul').hide(); $('h2').hide(); $('a.btnDown').click(function () { $('body').css('background&apos ...

"Utilize the hover functionality in React JS to track the mouse movement

I'm currently facing an issue with a design that involves a 6-column grid and text placed in front of it. The requirement is that when I hover over the text, the background of the corresponding grid column should change to an image. While this functio ...

Put a cookie in place to deter users from returning to the website

Looking for a way to prevent access to my contest site once the form has been submitted. Is there a way to achieve this? Thanks in advance ...

Integrating a form test with an XHR request following the resizing of an image for upload

I am currently facing an issue where I need to send both form input text and a client-side resized image to a php page. The image upload works fine, however, the text data appending seems to be causing problems. var xhr = new XMLHttpRequest(); xhr.onr ...

Ways to set a random value to a data attribute from a specified array while using v-for in Vue.js?

In my main Vue instance, I have a data attribute that consists of an array containing 4 items: var app = new Vue({ el: '#app', efeitosAos: ['fade', 'flip-up', 'slide-up', 'zoom-in'] ...

Steps for aligning floating DIVs in the center of a parent DIV

Why is the text alignment not working as expected when I have three divs within a parent div that need to be center aligned? If you'd like to see the issue in action, check out this Demo fiddle <div class="container_alt"> <div class= ...

Ways to display a collection of random images with a click of a button?

I've created a simple php webpage that is supposed to display random images from my images folder when a button is clicked. However, I'm facing an issue where no images are showing up and I can't seem to pinpoint the problem in my code. ...

html5 Showing and hiding div elements

Here is a snippet of code to consider: @using App.Models @model App.Models.AllPeopleViewModel @{ ViewBag.Title = "Index"; } <html> <head> </head> <body> @foreach (Customer person in Model.Content) { <div class=&qu ...

Ensure that the function's parameters are entered exclusively through TypeScript interfaces

How can I efficiently organize and maintain the function's arguments below without utilizing Typescript? Can this be achieved using Interfaces? // external file export interface TSomeFunctionArgs { someKey: string // there should also be a type ...

Is it possible to customize the default styling options in Tailwind?

I am currently working on a blog using NextJS, and I have encountered an issue with Tailwind's list style type. It seems that the default styling for list style type is set to list-none, resulting in my <ul> <li> elements not being styled ...

Vue Router does not enforce redirects

I am currently facing an issue where the requireAuth() function is being called repeatedly, causing a loop. I only want to display pages when the user is logged in. This is the code snippet I am using: // Routes const routes = [ { path: &apos ...

Unable to successfully change the Span Class

My webpage has the code snippet below, but it's not functioning as expected. I have tried two methods to change the span's class attribute, but they aren't working. Could someone please help me identify where the issue lies? :) <script l ...