windows 10 pro office 2019 pro office 365 pro windows 10 home windows 10 enterprise office 2019 home and business office 2016 pro windows 10 education visio 2019 microsoft project 2019 microsoft project 2016 visio professional 2016 windows server 2012 windows server 2016 windows server 2019 Betriebssysteme office software windows server https://softhier.com/ instagram takipçi instagram beğeni instagram görüntüleme instagram otomatik beğeni facebook beğeni facebook sayfa beğenisi facebook takipçi twitter takipçi twitter beğeni twitter retweet youtube izlenme youtube abone instagram

javascript / jQuery – What is the most efficiënt way to replace all the occurrences of a string in a body without replacing the entire body

Asked By: Anonymous

I want to replace all the occurrences of a certain string in a web page’s body without replacing the entire body (as it could destroy eventlisteners etc). Is there a way to do this and if so, what is the best one?

To give an example:

We have the following code:

<body>
    <div class="header">
        #parameter#
    </div>
    <div class="body">
        <div class="some-widget">
            we have some code here
            <div class="text">
                And also our #parameter#
            </div>
        </div>
    </div>
</body>

As mentioned, we could use something like

$('body').html($('body').html().replace(/#parameter#/g, 'Our parameter value'));

but that could render our some-widget useless.

We have no idea what the web page will look like structurally, so we cannot look for certain containers of our #parameter#

Ideally, I think we would perform a search on "#parameter#", get the parent element and then replace the parent elements html in the way mentioned above. I do not know if and how that is possible however. The closest I got was This question, but it didn’t get me much further.

Thanks!


Solution

Answered By: Anonymous

You can iterate over all text nodes and replace their nodeValue:

_x000D_

_x000D_

function getTextNodes(parent) {
    const walker = document.createTreeWalker(
        parent,
        NodeFilter.SHOW_TEXT,
        null,
        false
    );

    let node;
    const nodes = [];

    while(node = walker.nextNode()) {
        nodes.push(node);
    }
    return nodes;
}

for (const node of getTextNodes(document.body)) {
  node.nodeValue = node.nodeValue.replaceAll('#parameter#', 'foo');
}

_x000D_

<body>
    <div class="header">
        #parameter#
    </div>
    <div class="body">
        <div class="some-widget">
            we have some code here
            <div class="text">
                And also our #parameter#
            </div>
        </div>
    </div>
</body>

_x000D_

_x000D_

x000D

techinplanet staff


Windows 10 Kaufen Windows 10 Pro Office 2019 Kaufen Office 365 Lizenz Windows 10 Home Lizenz Office 2019 Home Business Kaufen windows office 365 satın al follower kaufen instagram follower kaufen porno