简体   繁体   中英

How to find and replace a string in HTML DOM element using javascript

Click the button to replace "blue" with "red" in the paragraph below:

<div id="main">
<p>Mr Blue has a blue house and a blue car.</p>
<p>Mr Blue has a blue house and a blue car.</p>
</div>
<button onclick="myFunction()">Try it</button>

 <script>
 function myFunction() {
     var str = document.getElementById("main");
     var x = str.document.getElementsByTagName("p");
     var res = x.innerHTML.replace(/blue/gi, "red");
     document.getElementsByTagName("p").innerHTML = res;
}
  </script>

   </body>
   </html>

I tried to replace the occurence of string "blue" with red in the document using DOM methods. I have not got the desired result. Could anyone please have a look at the code. Any help would be appreciated

There are multiple problems in your code.

To get p s from the div, you need to

str.getElementsByTagName("p");  //and not str.document...

The above statement will return a collection and not a single element. So you need to loop over the collection and do your replace.

for(var i=0; i<x.length; i++) {
    var res = x[i].innerHTML.replace(/blue/gi, "red");
    x[i].innerHTML = res;
}

Working example .

Update based on your comment (what is a loop) : Please use the tutorials here to get started.

Another way to do it is to ignore the p tags altogether and just do the replacement on the div's innerHTML, like so:

function myFunction() {
     var str = document.getElementById("main");
     var inner = str.innerHTML;
     var res = inner.replace(/blue/gi, "red");
     str.innerHTML = res;
}

here's a full example as well: http://jsfiddle.net/ek9b4/

This should work for you:-

var paras = document.getElementsByTagName('p');
    for (var i = 0; i < paras.length; i++) {
        paras[i].textContent = paras[i].textContent.replace(/blue/g,'red');
    };

Couple of things...

  • You can't call .document on str, which is already an object.
  • You'll need to iterate through the array of p elements, which you were almost grabbing correctly. :)

Something like this:

function myFunction() {
        var str = document.getElementById("main");
        var x = str.getElementsByTagName("p");
        for (i = 0; i < x.length; i++) {
            var text = x[i].innerHTML;
            x[i].innerHTML = text.replace(/blue/gi, "red");
        }

    }

You can see a working example here: http://jsfiddle.net/a942G/

Hope that helps!

getElementsByTagName returns a NodeList; you need to loop, using a for loop for example. But here's an alternative more re-usable approach that handles letter case:

// helper to convert NodeList to real array
var toArray = Array.call.bind([].slice)
// helper to query the DOM
var query = document.querySelectorAll.bind(document)

// uppercase first letter
var capitalize = function(x) {
  return x[0].toUpperCase() + x.slice(1)
}
// replace word and handle letter case
var replaceWord = function(word, replacement, str) {
  return str.replace(RegExp(word, 'gi'), function(m) {
    return /[A-Z]/.test(m) ? capitalize(replacement) : replacement
  })
}

// query all `p` tags and replace
toArray(query('p')).forEach(function(x) {
  x.textContent = replaceWord('blue', 'red', x.textContent)
})

Demo: http://jsbin.com/siveh/2/edit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM