Utilizing variable values in HTML and CSS to enhance a website's functionality

My current project involves modifying an HTML web resource for use in Dynamics 365. I need to replace a static URL with a dynamic value obtained via Javascript, specifically:

var URL = Xrm.Page.context.getClientUrl();

There are multiple instances within the resource where this replacement needs to happen, such as in this CSS snippet:

.aftertd {
  background: transparent url("REPLACETHIS/_imgs/imagestrips/grid_ctrl_imgs.png?ver=-1792584992") no-repeat scroll -171px -19px;
  height: 14px;
  overflow: hidden;
  width: 4px;
  cursor: col-resize;
  position: absolute;
  right: 0;
}
<th>
  <span ng-click="sort('createdon')" class="tdSpanTh">
  Date
    <img ng-show="sortKey=='createdon'" alt="The data is sorted in ascending order on this column" src="REPLACETHIS/_imgs/imagestrips/transparent_spacer.gif" ng-class="{'ms-crm-List-Sortable ms-crm-Image-Margin ms-crm-ImageStrip-sorting_up':!reverse,'ms-crm-List-Sortable ms-crm-Image-Margin ms-crm-ImageStrip-sorting_down':reverse}" style="visibility:visible;" title="The data is sorted in ascending order on this column">
  </span>
  <span class="aftertd pull-right"></span>
</th>

The goal is to substitute the static string REPLACETHIS (in the src attribute above) and the CSS property value with the URL variable's dynamic content.

I've attempted one approach like this:

document.body.innerHTML = document.body.innerHTML.replace(/REPLACETHIS/g, URL);

However, I'm curious if there might be a more efficient solution given that REPLACETHIS appears multiple times in the HTML file.

Answer №1

Here is a potential solution for you:

var replaceText = "REPLACETHIS";
var replaceWithURL = "URL";

var imageElements = document.getElementsByTagName("img");
for (var i = 0; i < imageElements.length; i++) {
  const img = imageElements[i];
  img.src = img.src.replace(replaceText, replaceWithURL);
}

var otherElements = document.querySelectorAll(".aftertd, .otherclass"); //comma-separated selectors
for (var i = 0; i < otherElements.length; i++) {
  const el = otherElements[i];
  var styles = window.getComputedStyle(el, null);
  el.style.background = styles.getPropertyValue("background").replace(replaceText, replaceWithURL);
}

//More generic approach:
var allHTMLElements = document.querySelectorAll("*");
for (var i = 0; i < allHTMLElements.length; i++) {
  const elem = allHTMLElements[i];
  for (var attribute of ["href", "src"]) { 
    var oldValue = elem[attribute];
    if (oldValue) elem[attribute] = oldValue.replace(replaceText, replaceWithURL);
  }

  var elementStyles = window.getComputedStyle(elem, null);
  for (var property of ["background", "background-image", "border-image"]) {
    var oldVal = elementStyles.getPropertyValue(property);
    if (oldVal) elem.style[property] = oldVal.replace(replaceText, replaceWithURL);
  }
}
.aftertd {
  background: transparent url("REPLACETHIS/_imgs/imagestrips/grid_ctrl_imgs.png?ver=-1792584992") no-repeat scroll -171px -19px;
  height: 14px;
  overflow: hidden;
  width: 4px;
  cursor: col-resize;
  position: absolute;
  right: 0;
}
<th>
  <span ng-click="sort('createdon')" class="tdSpanTh">
  Date
    <img ng-show="sortKey=='createdon'" alt="The data is sorted in ascending order on this column" src="REPLACETHIS/_imgs/imagestrips/transparent_spacer.gif" ng-class="{'ms-crm-List-Sortable ms-crm-Image-Margin ms-crm-ImageStrip-sorting_up':!reverse,'ms-crm-List-Sortable ms-crm-Image-Margin ms-crm-ImageStrip-sorting_down':reverse}" style="visibility:visible;" title="The data is sorted in ascending order on this column">
  </span>
  <span class="aftertd pull-right"></span>
</th>

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

React Native does not support Laravel Echo's listenForWhisper functionality

I have successfully implemented private channels and messaging in my Laravel App using websockets:serve. Now, I am attempting to enable whisper functionality for the typing status but encountering some issues. When sending a whisper: Echo.private('c ...

Is it possible to customize bootstrap classes for a unique bootstrap css design?

In my MVC4 project, I faced a situation where I had a global.css class with some classes that conflicted with Bootstrap after adding it. To resolve this, I created a new file called bootstrap_migration.css. In this file, I prefixed the Bootstrap classes wi ...

insert the "tr" element directly following the button

I am looking for a way to allow the user to add another input file right next to the button, so they can select and send multiple files at once. https://i.sstatic.net/TI4eJ.png I have tried using various solutions I found during my search but none of the ...

Two vertical divs stacked on top of each other, each expanding to the entire height and width of the browser window

Is there a way to set the width and height of two divs on a webpage to match the dimensions of the browser window, requiring scrolling to view the second div? In addition, how can I ensure that the content within these divs is vertically centered? To ach ...

Issue with AngularJS: The select dropdown fails to update the selected option when the bound scope variable changes

I am facing an issue with a select control in my Angular app. The options for the select are generated dynamically from an array of objects in the scope. When I try to pre-select a specific option on app init by changing a bound variable on the scope, it d ...

Developing HTML5 animation by utilizing sprite sheets

Struggling to create an engaging canvas animation with the image provided in the link below. Please take a look at https://i.stack.imgur.com/Pv2sI.jpg I'm attempting to run this sprite sheet image for a normal animation, but unfortunately, I seem to ...

Managing Numerous Dropdown Menus: Techniques and Tips

I'm currently working with MUI to design a navigation menu that contains dropdowns within certain links. However, I've encountered an issue where clicking on any button opens the same dropdown menu. Below is my code snippet: function Header() { ...

Javascript code has been implemented to save changes and address resizing problems

Code Snippet: <script> function showMe(){ document.querySelector('#change').style.display = ''; document.querySelector('#keep').style.display = 'none' document.querySelector('#change1').style.d ...

Mastering the Art of Aligning Avatars: Effortless Right Alignment

Here's the updated version of the navigation bar: <nav class="navbar navbar-expand-md navbar-dark bg-dark static-top"> <button class="navbar-toggler" type="button" data-toggle="collapse"> ...

Combining AngularJS with Servlets: A Seamless Integration

I am attempting to retrieve a JSON object from a servlet by calling a function through a link in my HTML code. Below is the HTML link that calls the fTest function: <td><a href="" ng-controller="minaplantaCtrl" ng-click="fTest(x.id_camion_descar ...

Utilizing the request module in Node.js with ExpressJS

Currently, I am in the process of creating a helper method within my code that will handle user authorization. This function, named "usePermissions", is being developed following the React approach but for backend functionality. Upon implementa ...

The "users" property or method has not been defined in Vue.js applications

During the development of my Vue.js shopping cart, I encountered an issue where I wanted to display the username in a label after the user provided correct information. However, I received the following error in Google Chrome: vue.js:634 [Vue warn]: Prope ...

Utilizing string interpolation within the parameters of an AJAX call

I have a locale variable that can hold values such as en, fr, or es. The goal is to include this locale key in an AJAX request as part of the data parameter. let locale = "en"; let name = "example"; $.ajax({ url: "/path", method: "PUT", data: {chara ...

What does the "done" callback function entail in Node.js?

Many npm packages commonly utilize a "done" callback function in their code. I find it challenging to grasp its purpose. For instance: passport.serializeUser(function(user, done) { done(null, user.id); }); From what I can gather: The "done" function a ...

There is a lack of definition for an HTML form element in JavaScript

Encountering an issue with a HTML form that has 4 text inputs, where submitting it to a Javascript function results in the first 3 inputs working correctly, but the fourth being undefined. Highlighted code snippet: The HTML section: <form action="inse ...

Revamp the md-select Container

Hello there! I'm looking for a stylish way to revamp the design of the md-select Window. Specifically, I aim to customize the background and hover effects. Despite my attempts to modify the .md-select-menu-container in CSS, it proved unsuccessful. I ...

jQuery smoothly sliding downward from the top to the bottom

http://jsfiddle.net/Hx65Q/3/ Is there a way to make the slider open from the top instead of the left side? $("button" ).click(function() { $('.login').toggle('slide', { duration: 1000, easing: 'easeOutBounce', }); ...

Notifications will be displayed with Alertifyjs to the individual who activated them

Just diving into the world of nodejs and express framework, so I appreciate your patience as I navigate through this learning process. I've implemented the alertifyjs library to display notifications for different alerts on my site. However, I&apos ...

Error occurring when attempting to pass messages within an iframe on a sandboxed page in a Chrome extension

Whenever I try to utilize my popup page for a chromium extension as a conduit for communication between the background page and a page shown within an iframe on the popup, I encounter the following error. I required a sandboxed environment to execute Vue.j ...

Is the DOMContentLoaded event connected to the creation of the DOM tree or the rendering tree?

After profiling my app, I noticed that the event is triggered after 1.5 seconds, but the first pixels appear on the screen much later. It seems like the event may only relate to DOM tree construction. However, this tutorial has left me feeling slightly con ...