I’m trying to change paragraph text in a for each loop. This seems like a simple issue (specific to JS?). I’m new to this language, coming from Matlab and Java. Fiddle attached. Any help is appreciated.
https://jsfiddle.net/npkx3of4/1/
function myFunction() {
var ps = document.getElementsByClassName('.test');
for (var p of ps) {
p = p.replace('a', '<span style="color:blue;">b</span>');
}
alert("Working?");
return null;
}
>Solution :
-
getElementsByClassName('.test')should begetElementsByClassName('test'). -
You should be assigning the result of replacing the
innerHTMLof the paragraph back to theinnerHTMLof the paragraph.
function myFunction() {
var ps = document.getElementsByClassName('test');
for (var p of ps) {
p.innerHTML = p.innerHTML.replace('a', '<span style="color:blue;">b</span>');
}
alert("Working?");
return null;
}
<h1>Test</h1>
<hr>
<p class="test">a</p>
<button type="button" onclick='myFunction();'>Click Me!</button>