anson920520 anson920520 - 6 months ago 9
HTML Question

Cannot use .replace() on all elements contain same class

i am using the method below to replace all

<p>
tags' comma to hash

var node = document.getElementByClassName('discovereedKeywords');
node.innerHTML = node.innerHTML.replace(/,/g, '#');


and in reality those
<p>
tags are actually generate by a for loop, but my method only change the first
<p>
tag it found therefore i tried something like below

Consider the html looks like this

<p class="discovereedKeywords"> apple,banana,oranger</p>

<p class="discovereedKeywords"> apple,oranger,oranger</p>

<p class="discovereedKeywords"> kiwi,melon,pinapple</p>


Javascript

for (var i=0; i <data.result.data.length; i++){
var node[i] = document.getElementByClassName('discovereedKeywords');
node[i].innerHTML = node.innerHTML.replace(/,/g, '#');
}

Answer

$('p').text(function(_, txt){
   return txt.replace(/,/g, '#');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="discovereedKeywords"> apple,banana,oranger</p>

 <p class="discovereedKeywords"> apple,oranger,oranger</p>

 <p class="discovereedKeywords"> kiwi,melon,pinapple</p>

In jQuery, you can use text() method:

$('p').text(function(_, txt){
   return txt.replace(/,/g, '#');
});
Comments