I have this table that I echoed in a page I’m making, and in the output is a series of products separated by a comma (,)
Here is the code for the column:
<td class='listord'>" . $row["OrderList"] . "</td>
here is a sample ouput:
PRODUCT1,PRODUCT2,PRODUCT3
expected output:
PRODUCT1 PRODUCT2 PRODUCT3
This is my current code but it doesn’t seem to work:
let str = document.getElementsByClass("listord"); for (var i = 0; i < str.length; i++) { let result = str[i].innerText.replace(/,/g, "<br>"); str[i].innerText = result; }
What am I doing wrong?
Advertisement
Answer
As CBroe says in the comments, the JS doesn’t work primarily because getElementsByClass
isn’t a real function, not because there’s anything wrong with the regular expression in your replace
call.
Always check your browser’s Console (in its Developer Tools) for errors when working with JavaScript, because this would have shown up there – e.g. in Chrome you’d get the following message:
Uncaught TypeError: document.getElementsByClass is not a function
Also, always check documentation to remind yourself of the exact name.
Another problem you’ll have is that since you’re trying to replace the comma with a HTML tag, and are expecting the browser to parse that and show the text on separate lines, you need to use innerHTML
instead of innerText
, otherwise your replacement will be interpreted as plain text instead of live HTML.
Demo:
let str = document.getElementsByClassName("listord"); for (var i = 0; i < str.length; i++) { let result = str[i].innerHTML.replace(/,/g, "<br/>"); str[i].innerHTML = result; }
<table> <tr> <td class='listord'>PRODUCT1,PRODUCT2,PRODUCT3</td> </tr> </table>
N.B. As I and others have said in the comments though, a properly normalised database design would not involve storing multiple data items in a single column in comma-separated format to begin with.