Skip to content
Advertisement

How to use JavaScript to get element by class name and then split commas onto new lines?

Let’s say I have this HTML output:

JavaScript

How would I use a simple script to replace the comma and space inside each ‘blog-post-title-link’ class with a line break? So instead of looking like this:

John Doe, MD

Jane Doe, MD

Jane Doe Smith, MD

The output would be:

John Doe
MD


Jane Doe
MD


Jane Doe Smith
MD


UPDATED NOTE: The names and the MD in the simple example above should not be hard-coded. Sorry I didn’t mention that originally.

Finally, if I wanted add a style to the split text so that the “MD” lines above appear in a different color, I’m wondering if I could use the same function and just use a <span> or <div> tag to wrap the split text rather than just a line break. Any help is much appreciated, as I don’t have access to change the original text.

Advertisement

Answer

This queries all blog-post-title-link classes, replacing commas in their HTML with its following text, wrapped in a div:

JavaScript

To get a different color, you could style a div like this:

JavaScript

JavaScript
JavaScript
JavaScript

Here’s the jQuery equivalent:

JavaScript

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement