Adjusting specific sections of a container in real-time

Fiddle: https://jsfiddle.net/1b81gv7q/

Sorry for the slightly cryptic title; I couldn't come up with a better way to phrase it.

Imagine this scenario: there's a container with content that needs to be dynamically replaced.

If I wanted to replace everything within the template DOM node, while keeping the static-container intact, how would I achieve that? It's important to note that simply targeting h1 and p won't cut it. The entire contents of the template container need to be swapped, except for the static-container, which should stay in place as the last child of template.

I'm not looking for solutions that rely on React, Vue, Angular, or any other framework. Strictly interested in pure JavaScript or jQuery solutions.

$('button').click(function() {
  let newTemplate = $('.new-template').html();
  $('.template').html(newTemplate);
});
.new-template {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="template">
    <h1>header #1</h1>
    <p>some text for #1</p>
    <div class="static-container">
      <div>
        <p>a b c 1 2 3</p>
        <p>d e f 4 5 6</p>
      </div>
    </div>
  </div>
</div>

<button>change template</button>

<div class="new-template">
  <h1>header #2</h1>
  <p>some text for #2</p>
  <div class="static-container"></div>
</div>

Answer №1

To create a newTemplate variable, you must include the content of the static-container in that variable (combine all the elements needed to display in the new template).

var staticContainer = $('.static-container')
$('button').click(function() {
  let newTemplate = $('.new-template').html() + staticContainer.html();
  $('.template').html(newTemplate);
});
.new-template {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="template">
    <h1>header #1</h1>
    <p>some text for #1</p>
    <div class="static-container">
      <div>
        <p>a b c 1 2 3</p>
        <p>d e f 4 5 6</p>
      </div>
    </div>
  </div>
</div>

<button>change template</button>

<div class="new-template">
  <h1>header #2</h1>
  <p>some text for #2</p>
  <div class="static-container"></div>
</div>

Answer №2

To efficiently update the content within a template, we can loop through each child element and check if it has the class .static-container before making any replacements:

document.querySelector('button').onclick = function() {
  const newTemplate = document.querySelector('.new-template');
  [...document.querySelector('.template').children].forEach((child, i) => {
    if (child.matches('.static-container')) return;
    child.innerHTML = newTemplate.children[i].innerHTML;
  });
};
.new-template {
  display: none;
}
<div class="wrapper">
  <div class="template">
    <h1>header #1</h1>
    <p>some text for #1</p>
    <div class="static-container">
      <div>
        <p>a b c 1 2 3</p>
        <p>d e f 4 5 6</p>
      </div>
    </div>
  </div>
</div>

<button>change template</button>

<div class="new-template">
  <h1>header #2</h1>
  <p>some text for #2</p>
  <div class="static-container"></div>
</div>

Answer №3

To ensure that the static-container class is the only remaining element in the DOM, you can loop through and remove any other elements. Once this is done, you can prepend your new template to the static-container so it remains as the last element.

$('button').click(function() {
  $(".template").children().each(function() {
    if(!$(this).hasClass("static-container")) {
      $(this).remove();
    }
  });

  var newTemplate = $('.new-template').html();
  $('.template').prepend(newTemplate);
});

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

Switch your attention to the following input text using AngularJS

In my controller, I have an object variable called `myObject` with 3 input text fields in the user interface. I am looking for a way to automatically shift the focus to the next input field once the current one reaches its maximum length. var myObject = ...

Vue Component Update DisorderI hope this meets your expectations

Below is my code using Bootstrap, Vue, and Axios: SETUP: *Please disregard the tab-contents in component_a main.js Vue.component('component_a', { props: ['info'], template: `<div> // Component A template code here } ...

Node.js, sigma.js, and the typescript environment do not have a defined window

When attempting to set up a sigma.js project with node.js in TypeScript, I encountered a reference error after starting the node.js server: ts-node index.ts The problem seems to be located within the sigma\utils\index.js file. <nodejsproject& ...

Establishing default parameters for angular pipes

Is there a way to establish default settings for an angular pipe without creating a custom one myself? I frequently utilize the currency pipe in this manner {{ price | currency:'EUR':'symbol':'0.2-2':'de' }} I&apo ...

Bring in d3 along with d3-force-attract

Recently, I have installed D3 along with d3-force-attract. npm install @types/d3 -S npm install -S d3-force-attract I am currently facing an issue with importing d3 force attract as it is not recognized as a typescript module, unlike d3 itself. The inco ...

A guide to setting up checkbox input in Vue 3 so that it toggles between checked and unchecked states when an

I'm in the process of creating a div container that will contain both an image and a checkbox input element. The checkbox input has a click handler that passes a value to a function, as well as a :value binding which sends the value to an array named ...

The alignment of two elements is off in mobile display

Why aren't my two divs centered in mobile view? I am using Vuetify CSS flex helper justify-center to try and achieve it, but it doesn't seem to be working. Even when I use justify-sm-center, it still doesn't work. What am I missing? <v-co ...

Is there a problem with css3 opacity transition in Webkit browsers?

While exploring alternative ways to modify the Bootstrap 3 carousel, I stumbled upon a technique that achieves a 'fade' effect instead of the usual 'slide'. However, in webkit browsers, the transition may appear choppy or flicker betwee ...

Execute a zoom out action by pressing the (Ctrl) and (-) keys simultaneously in Javascript

I'm trying to figure out how to simulate a Ctrl - zoom out using Javascript. I've noticed that using the style zoom property or the transform property gives different results with white space in the corners, rather than the smooth zoom out effect ...

Merge topics together in RxJS like zip

Is it possible to create an observable that combines two subjects in a unique way, different from the zip function? The goal is to combine two subjects so that when both have emitted values, the latest of their values is emitted. Then, after both emit at ...

Verify if the date surpasses the current date and time of 17:30

Given a date and time parameters, I am interested in determining whether that date/time is greater than the current date at 17:30. I am hoping to achieve this using moment js. Do you think it's possible? This is what I have been attempting: let ref ...

Jest - Silence greets the test results

Struggling with Jest has been a common theme for me ever since I first attempted to use it. Regardless of the tests I run or the options I try to pass to Jest, I never seem to get the expected 'Pass' or 'Fail' results in the console. In ...

Problem with roles assigned through reactions on Discord

I've been working on a discord bot reaction roles command and everything seems to be going smoothly, except for one issue that I'm facing. After booting up the bot and running the command to create the embed, everything works fine. However, when ...

Finding the return value from a .asp file using ajax

Why is it difficult to retrieve the return value from .asp? Here is the JavaScript code I am using: $('#loginID').click(function(){ var userID = $("#userId").val(); var passID = $("#passwordId").val(); var myURL = "http://ipaddress/asp/ ...

Generating a JSON object through the comparison of two other JSON objects

I need to create a new JSON object called selectedProductAttributes, which is generated by comparing the contents of a second JSON object (selectedProductAttributesNames) with a third object (allProductAttributes). Let me provide some examples to make this ...

The HTML canvas drawImage method overlays images when the source is modified

Trying to implement a scroll animation on my website, I came across a guide for creating an "Apple-like animation" using image sequences. Even though I'm new to Angular, I attempted to adapt the code to work with Angular. However, instead of animatin ...

Displaying JSON keys and values individually on an HTML page

Looking to display a JSON array in HTML using ngFor TypeScript : import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-ng-for', templateUrl: './ng-for.component.html', styleUrls: ['./ng-for ...

Bootstrap modal experiencing technical difficulties

I am experiencing issues with my bootstrap modal. It seems to be malfunctioning, almost as if the CSS or JavaScript files are not being recognized. I have tried various solutions but have been unable to resolve the problem. I even attempted using the examp ...

Conceal the browser scrollbars

When I have two DIVs on my webpage that are larger than a browser window, it results in a horizontal scrollbar being displayed. How can I hide this browser scrollbar for the first DIV while still showing it for the second one? For example, if I have two ...

Tips for navigating a user to a different HTML page using JSP code?

In my html page Login.html, I have set up a simple login form with username and password fields, along with a submit button. When the user clicks on the submit button, it triggers a JSP page named Login.jsp to validate the entered credentials against an ...