replace javascript

2

Hello, I want to hide a text that contains "(numbers)", get a method, but only works on the first element, the others still showing, how to loop for all elements? follow my code

 <div id="mydiv">
 <a  href="#" id="demo"> Mr Blue has a blue house, (0123dddddd4) and/ a blue car </a>   
 </div>


 <div id="mydiv">
  <a  href="#" id="demo1"> Mr Blue has a blue house, (0123dddddd4) and/ a blue car </a> 
 </div>




 <script>
 function myFunction() {
    var str = document.getElementById("demo").innerHTML;
    var res = str.replace( /\(.*\)/, '' );
    document.getElementById("demo").innerHTML = res;
 }

 </script>
    
asked by anonymous 11.06.2015 / 18:58

2 answers

2

The .getElementById() method returns only one element, the first one to find. You have to use another method like .querySelectorAll() and a loop to iterate all the elements you want.

Note that id must be unique, you can not repeat elements with the same id . I suggest you change to class or use the DOM structure for your selector.

A version of what you want to do would be, for example:

function limpar(el) {
    var str = el.innerHTML;
    var res = str.replace(/\(.*\)/, '');
    el.innerHTML = res;
}

var links = document.querySelectorAll('.mydiv a');
[].forEach.call(links, limpar);

jsFiddle: link

In this suggestion, I use the .forEach() imported from Array methods, you can do with a loop like this:

var links = document.querySelectorAll('.mydiv a');
for (var i = 0; i < links.length; i++) {
    limpar(links[i]);
}

jsFiddle: link

    
11.06.2015 / 19:03
1

If you want to do this treatment for all a elements, you can use getElementsByTagName()

Example:

function myFunction() {
    var as = document.document.getElementsByTagName('a');

    for (var i=0; i < as.length; i++) {
         as[i].innerHTML = as[i].innerHTML.replace( /\(.*\)/, '' );
    }
}
    
11.06.2015 / 19:04