What steps do I need to take to develop a syntax similar to Vue.js using only plain JavaScript?

<div id="">
    <span>{{msg}}</span>
</div>

Assume that {{msg}} is a variable in JavaScript. Now, I aim to locate the parent tag of {{msg}} and replace its content with a new value using innerHTML, where {{msg}} serves as an identifier.

Sample JavaScript demonstration:

<script>
 var msg = "This is updated information";
 {{msg}}.parentElement.innerHTML=msg;
</scritp>

This code snippet is not functional, it is purely for explanatory purposes.

Answer №1

If you're looking to update text within an element using jQuery, it can be done easily with the following code:

var message = "This is the updated content";

$(`span:contains(${message})`).html("New Text");

Alternatively, if you prefer to use pure JavaScript, you can achieve the same result like so:

var spanTags = document.getElementsByTagName("span");
var message = "This is the updated content";
var foundElement;

for (var i = 0; i < spanTags.length; i++) {
  if (spanTags[i].textContent === message) {
    foundElement = spanTags[i];
    break;
  }
}

Once you have identified the desired element in the variable foundElement, you can proceed to update its text as shown below:

 if (foundElement) {
     foundElement.innerHTML = "New text";
 }

Answer №2

One effective method is to view the entire document as a string initially, and then re-parse it once modifications are complete.

The utilization of the .innerHTML property acts as an HTML decompiler or compiler based on whether you are reading from or writing to it. For instance, if there are variables in the document that need replacing, you can execute:

let vars = {
    msg: msg,
    test_number: 10,
    test_str: 'hello'
};

let htmlText = document.body.innerHTML;

// Locate each variable (assuming format is {{var_name}})
// and substitute with its corresponding value:

for (let var in vars) {
    let pattern = '\\{\\{\\s*' + var + '\\s*\\}\\}';
    let regexp = new RegExp(pattern, 'g');
    htmlText = htmlText.replace(regexp, vars[var]);
}

// Re-parse the modified HTML text to update the page
document.body.innerHTML = htmlText;

This approach efficiently implements the {{var}} syntax. As long as the syntax is properly designed to prevent interference with HTML tags within the document, this method should work effectively.

There may be some performance drawbacks due to redrawing the entire page, but unless this action is constant (e.g., during animations), the impact would generally be minimal. It is advisable to benchmark the code for performance concerns.


An alternative technique involves solely processing text nodes to avoid unintended alterations to actual HTML tags. One way to achieve this is by creating a recursive descent parser. Because all nodes have a .childNodes attribute and the DOM functions as a tree structure (non-cyclic), searching for the specified syntax throughout the entire DOM is feasible.

I will not provide a detailed code example for this process since it can become quite intricate, but the basic concept is outlined below:

const TEXT_NODE = 3;

let vars = {
    msg: msg,
    test_number: 10,
    test_str: 'hello'
};

function walkAndReplace(node) {
    if (node.nodeType === TEXT_NODE) {
        let text = node.nodeValue;
        
        // Implement necessary logic for handling text here.
        // You can integrate the RegExp functionality from the earlier example
        // for straightforward text substitutions. If new DOM elements like <span> or <a> are needed, remove
        // the current node from its .parentNode, generate the required
        // elements, and subsequently add them back to the .parentNode.
    } else {
        if (node.childNodes.length) {
            for (let i = 0; i < node.childNodes.length; i++) {
                walkAndReplace(node.childNodes[i]); 
            }
        }
    }
}

walkAndReplace(document.body);

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

Utilizing Laravel's auth() function within a Vue component: Step-by-step guide

Before, I used Auth in Laravel blade view to control button visibility based on user permissions. Now that I am learning Vue, I am curious about how I can achieve the same functionality in a Vue Component. I want to replicate this logic from my blade file ...

Guide on incorporating interactive visuals or features within a panoramic image viewer through the use of THree.js and webGL

Seeking advice on how to incorporate more images and hyperlinks within a panoramic viewer, similar to the examples below: This particular link Panorado js viewer. I have noticed that these viewers feature embedded hyperlinks and overlays, I have attempt ...

The JSON data script is not functioning properly

Is this JSON formatted correctly? Why is it not displaying in the element with #id? I found a similar code snippet on https://www.sitepoint.com/colors-json-example/, copied and replaced the values but it's not functioning. Can anyone shed some light o ...

What is the best way to display compiled Transcluded HTML in Angular?

I am facing a challenge in trying to display customized HTML content using Angular directives for nesting divs multiple times. When I execute the code below, the transcluded tag is displayed correctly but the browser output shows the string text " ". I att ...

Building a Dynamic Checkbox Validation Feature in Angular Using Data retrieved from an API

Currently, I have a function that retrieves and displays a list obtained from an API: displayEventTicketDetails() { this.Service .getEventTicketDetails().subscribe((data: any) => { this.eventTicketDetails = data.map(ticket => ticket. ...

Regular expressions: Capturing characters that come after and before a designated symbol

Is there a way to extract all letters, both before and after an underline "_", in JavaScript using Regex while excluding specific words like "pi", "\Delta" and "\Sigma"? How can this be achieved in Regex JS? /\b([^e|_|\d|\W])&bso ...

Passing parameters in a jQuery function through a button click

I am trying to figure out how to pass the @item.Id value as a parameter in the click function for a button. Here is the code snippet: <button id="buttonEdit" style="color:darkgreen" data-toggle="modal" data-target="#Ed ...

What kind of registration does React Hook Form use?

When utilizing react-hook-form alongside Typescript, there is a component that passes along various props, including register. The confusion arises when defining the type of register within an interface: export interface MyProps { title: string; ... ...

Modify route title and component if user is authenticated

I've successfully implemented a login feature in my Nativescript-Vue application that utilizes the RadSideDrawer component. My current challenge is to change the route from 'Login' to 'Logout', and I'm struggling to find a wa ...

Error: The route cannot be established within an asynchronous function

The following code snippet is from the api.js module, responsible for creating a test route: 'use strict'; module.exports = function (app) { console.log("before route creation"); app.get("/api/test", (req, res) => { ...

How to toggle the visibility of an element in an array using AngularJS and JavaScript

Is there a way to show additional information when an item in ng-repeat is clicked, and then hide this extra info when the mouse leaves that same item? One issue I am facing with the code snippet below is that when a user clicks on a different item, it al ...

Is there a way for me to detect when the progress bar finishes and execute a different function afterwards?

After clicking a button in my Javascript function, the button disappears and a progress bar is revealed. How do I trigger another function after a certain amount of time has passed? $('#go').click(function() { console.log("moveProgressBar"); ...

Creating animated direction indicators in the "aroundMe" style with ngCordova

I am attempting to recreate a compass or arrow similar to the one featured in the AroundMe Mobile App. This arrow should accurately point towards a pin on the map based on my mobile device's position and update as I move. I have been struggling to fi ...

Adjust Sidebar Height to Match Document Height (using React Pro Sidebar)

Having an issue with the height of a sidebar component in Next.js using React Pro Sidebar. It seems to be a JavaScript, HTML, and CSS related problem. I've tried several suggested solutions from Stack Overflow, but none of them seem to work. Surprisin ...

What is the best way to ensure the network is idle after clicking on an element in puppeteer?

Is there a way to wait for network idle after clicking on an element in puppeteer? const browser = await puppeteer.launch({headless: false}); await page.goto(url, {waitUntil: 'networkidle'}); await page.click('.to_cart'); //Clicking o ...

The error handler in AngularJS $http service is always left wanting for a call

Here's the code snippet I'm currently using: $http .post('/api/login', $scope.user) .success(function (data, status, headers, config) { // code }) .error(function (data, status, headers, config) { // code }); It seems to be functi ...

Create eye-catching banners, images, iframes, and more!

I am the owner of a PHP MySQL website and I'm looking to offer users banners and images that they can display on their own websites or forums. Similar to Facebook's feature, I want to allow users to use dynamic banners with links. This means the ...

The function is not recognized in C# programming language

Whenever I try to trigger functions by clicking buttons, nothing seems to happen and an error message appears in the console. Uncaught ReferenceError: AddressInputSet is not defined at HTMLButtonElement.onclick I'm new to this and could use ...

Using a self-invoking function in JavaScript with addEventListener

I'm struggling to get an Event Listener to self invoke a function and work correctly. Although the following code runs the function, the Event Listener is not functioning as expected: window.addEventListener("resize", (function () { document.getElem ...

The issue with MUI material autocomplete not functioning properly when onBlur is triggered

Although the onFocus parameter is working fine in material autocomplete, I'm facing an issue with the onBlur parameter. Can someone explain why this might be happening and provide a correct solution to implement it? <Autocomplete onBlur={() ...