-1

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

Let's think msg is variable of JavaScript and now I want to get the parent tag of {{msg}} and push a new value by innerHTML, here {{msg}} working as an identity.

demo JavaScript example: <script> var msg = "This is update data"; {{msg}}.parentElement.innerHTML=msg; </scritp>

This is not actual JavaScript code, only for better understanding.

norbitrial
  • 14,716
  • 7
  • 32
  • 59
Muhibbullah
  • 1
  • 1
  • 3
  • Possible duplicate of ["Variable" variables in Javascript?](https://stackoverflow.com/questions/5187530/variable-variables-in-javascript) – VLAZ Oct 14 '19 at 07:01
  • Actually, after re-reading the code sample, I'm not sure that the dupe is correct. Mostly because I'm not sure how it's supposed to function - what is `{{msg}}` supposed to resolve to? The element that holds `msg`? The `msg` text node? Even then, is it *any* element that holds `msg` regardless of its type or why it does that, or is it the specific binding defined with the `{{msg}}` template? Also, `msg` is defined in scope and it's just a string, so I don't know how it's going to be resolved as "something out of scope". I'm unsure how this is supposed to work. – VLAZ Oct 14 '19 at 07:04

2 Answers2

0

You can use jquery easily to find that element and then replace the text

var msg = "This is update data";

$(`span:contains(${msg})`).html("Its New");

In javascript:

var spanTags = document.getElementsByTagName("span");
var msg = "This is update data";
var found;

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

Now, you have found that element in found and you can now change its text

 if (found) {
     found.innerHTML = "New text";
 }
Bilal Siddiqui
  • 3,579
  • 1
  • 13
  • 20
  • 1
    `.innerText` is an HTMLElement property, not a jQuery method. For jQuery, you should use `.text()` while if you *are* using the HTMLElement, then you should probably use `.textContent` as it's more consistent than `.innerText` – VLAZ Oct 14 '19 at 07:06
  • I need answer in core javascript, code you help me? – Muhibbullah Oct 14 '19 at 07:06
  • i want to catch the tag "{{msg}}" according to {{ because here can be any type of tag but "{{somthing}}" this my common syntex. – Muhibbullah Oct 14 '19 at 07:51
  • @MuhibbullahAnsary in that case you need to traverse for each element rendered. Yo should consider id/or class for better performance – Bilal Siddiqui Oct 14 '19 at 08:47
0

The simplest approach is to treat the entire document as a string and then re-parse it when you're done.

The .innerHTML property is both an HTML decompiler and compiler depending on weather you're reading or writing to it. So for example if you have a list of variables that you want to replace in your document you can do:

let vars = {
    msg: msg,         // pass value as variable
    test_number: 10,  // pass value as number
    test_str: 'hello' // pass value as string
};

let htmlText = document.body.innerHTML;

// find each var (assuming the syntax is {{var_name}})
// and replace with its value:

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

// Now re-parse the html text and redraw the entire page
document.body.innerHTML = htmlText;

This is a quick, simple but brutal way to implement the {{var}} syntax. As long as you've correctly specified/designed the syntax to make it impossible to appear in the middle of html tags (for example <span {{ msg > hello </ }} span>) then this should be OK.

There may be performance penalties redrawing the entire page but if you're not doing this all the time (animation) then you would generally not notice it. In any case, if you are worried about performance always benchmark your code.


A more subtle way to do this is to only operate on text nodes so we don't accidentally mess up real html tags. The key to doing this is to write your own recursive descent parser. All nodes have a .childNodes attribute and the DOM is strictly a tree (non-cyclic) so we can scan the entire DOM and search for the syntax.

I'm not going to write complete code for this because it can get quite involved but the basic idea is as follows:

const TEXT_NODE = 3;

let vars = {
    msg: msg,         // pass value as variable
    test_number: 10,  // pass value as number
    test_str: 'hello' // pass value as string
};

function walkAndReplace (node) {
    if (node.nodeType === TEXT_NODE) {
        let text = node.nodeValue;

        // Do what you need to do with text here.
        // You can copy the RegExp logic from the example above
        // for simple text replacement. If you need to generate
        // new DOM elements such as a <span> or <a> then remove
        // this node from its .parentNode, generate the necessary
        // objects then add them back to the .parentNode
    }
    else {
        if (node.childNodes.length) {
            for (let i=0; i<node.childNodes.length; i++) {
                walkAndReplace(node.childNodes[i]); // recurse
            }
        }
    }
}

walkAndReplace(document.body);
slebetman
  • 109,858
  • 19
  • 140
  • 171