replace javascript

Asked

Viewed 140 times

2

Hello, I want to hide a text that contains "(numbers)", get a method, but only works in the first element, the others continue showing, how to make a loop for all elements ? follows 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>

2 answers

2


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

Note that id have to be unique, you can’t repeat elements with the same id. I suggest you switch 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: http://jsfiddle.net/3m3pc7bp/

In this Management 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: http://jsfiddle.net/3m3pc7bp/1/

1

If you want to do this treatment for all elements a, you can use the 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( /\(.*\)/, '' );
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.