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

Locate an original identifier using Selenium WebDriver

In search of a distinctive identifier for the "update profile picture button" on my Facebook account to utilize it in automation testing with Selenium WebDriver and Java. I attempted driver.findElement(By.className("_156p")).click();, but unfortunately, i ...

Replace the bullet icon with a double quote symbol

My HTML List needs a different look - I want to change the bullet icon into a double quote icon. A website that I found interesting is this one. Here's the CSS code I have: .listStyle li:before { list-style: none; content: "\00BB"; } < ...

Designing a unique customized top navigation bar in Magento 1.9.2

I recently attempted to create a unique top menu in magento 1.9.2 by modifying the Navigation.php file located at app/code/core/Mage/catalog/Block/. I added some custom classes in an effort to customize the menu. In order to achieve this customization, I ...

Laravel 5: Encounter with SQLSTATE[23000]: Violation of integrity constraint, foreign key restriction failed

I am currently working on implementing an upvote/downvote system using AJAX in Laravel 5. To display the voting buttons, I have integrated a jQuery plugin which can be found at this link: https://github.com/janosgyerik/jquery-upvote However, I have encoun ...

Challenges in establishing the initial connection between Express.js and MongoDB

Having spent a significant amount of time researching how to set up MongoDb in an Express/NodeJs application, I believed I had a good understanding of how to implement it efficiently. I decided to initialize my mongodbConnection in the WWW file provided by ...

Instructions for adding a unique custom external CSS link, such as Bootstrap CSS, to a specific REACT component

Is it possible to incorporate custom CSS from the Bootstrap website into a React component? Since this CSS file cannot be imported directly, what steps should I take to include it? <link href="https://getbootstrap.com/docs/4.5/dist/css/bootstrap. ...

Update the HTML content dynamically from the backend without the need for AJAX polling

Creating a dashboard for CRM that allows admins to view and process all orders is my current project. One key requirement is the ability to notify online admins about new orders as soon as they are placed, without having to refresh the page. I am aware th ...

Implementing server-side validation measures to block unauthorized POST requests

In my web application using angular and node.js, I am in the process of incorporating a gamification feature where users earn points for various actions such as answering questions or watching videos. Currently, the method involves sending a post request t ...

How can I modify the custom CSS to adjust the color of a Font Awesome icon?

Hello everyone! I am new to coding and I have a question for the Stack Overflow community. I am trying to customize the color of my Font Awesome icons on the homepage of my WordPress theme (Arcade Pro) using the custom CSS editor. Can anyone provide me w ...

Changing JSON variable letter case to lowercase using C#

Utilizing the JSONPEncoderFactory and JSONPBehavior method has allowed me to incorporate JSONP into WCF seamlessly. Everything is set up correctly and my service successfully returns data without any issues. However, I am faced with the challenge of conve ...

Converting JSON to string in Typescript is causing an error where type string cannot be assigned to type '{ .. }'

Here's the code snippet I'm working with: interface ISource extends IdModel { source_type_id: number; network_id: number; company_connection_id: number; feed_id: number; connection_id: number; feed_ids: number[]; name: string; tag ...

Listening to events on the iterative variable of NgFor directive in Angular 2

Angular2 has been my latest exploration in solving a unique data binding challenge. In my UI, I've presented a javascript array of objects like a database recordset in an HTML table. Each row contains menus and inputs allowing users to modify the rec ...

Storing information in the DOM: Choosing between Element value and data attribute

When it comes to storing values in a DOM element, we have options like using the data attribute. For example, $("#abc").data("item", 1) can be used to store values and then retrieve them with $("#abc").data("item"). However, I recently discovered that th ...

Babel continues to encounter issues with async/await syntax, even with all the necessary presets and plugins installed

I am encountering a compiler error while attempting to compile an async/await function using Babel. Below is the function in question: async function login(username, password) { try { const response = await request .post("/api/login") . ...

Updating Mysql through REST API/JWT using PUT method is not possible

I have been attempting to send an update request using Jwt (Tokens) and Node.Js with a backend in mysql. While Postman confirms that the record has been successfully updated, I am unable to locate where the actual update occurred. No changes seem to be ref ...

Retrieving object key value from an array using Underscore.js

Hey there, I'm facing a challenge where I need to extract the values of wave1 and wave2 from an array using underscore.js. array = [{"id":1,"name":"Monoprix", "pdv":16,"graph":[{"wave1":22,"wave2":11}]} ; I attempted the following: $scope.wave1 = a ...

Compilation of Angular 6 project is failing due to error TS1005: Expected ',' instead of the symbol used

I keep encountering an error message whenever I try to compile my code. ERROR in src/app/form/form.component.ts(22,39): error TS1005: ',' expected. Below is the snippet of code where the error is pointing: import { Component, OnInit } from &ap ...

Toggle visibility of div content when hovering over a link by leveraging the data attribute, with the div initially visible

I have a collection of links: <p><a href="#" class="floorplan initial" data-id="king"><strong>King</strong></a><br> 4 Bedrooms x 2.5 Bathrooms</p> <p><a href="#" class="floorplan" data-id="wood">< ...

Unable to deploy a node.js package via a jenkins job

I'm looking to set up a Jenkins job that will publish a package to npmjs.com. The source code for the package is located in a GitHub repository. While I am able to successfully publish the package from my personal computer by running 'npm publis ...

Dropzone failing to verify the maximum file limit

I am currently using dropzone to upload files on my website. I have limited the number of files that can be uploaded to a maximum of six. The code works perfectly when uploading one image at a time, but if I select more than six images by holding down the ...