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:

<h3 class="blog-post-title">
<a href="https://www.link1.com" class="blog-post-title-link">John Doe, MD</a>
</h3>

<h3 class="blog-post-title">
<a href="https://www.link2.com" class="blog-post-title-link">Jane Doe, MD</a>
</h3>

<h3 class="blog-post-title">
<a href="https://www.link3.com" class="blog-post-title-link">Jane Doe Smith, MD</a>
</h3>

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:

document.querySelectorAll('.blog-post-title-link').forEach(function(obj) {
  obj.innerHTML = obj.innerHTML.replace(/,(.+)/, (_, s) => `<div>${s}</div>`);
});

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

a div {
  color: red;
}

document.querySelectorAll('.blog-post-title-link').forEach(function(obj) {
  obj.innerHTML = obj.innerHTML.replace(/,(.+)/, (_, s) => `<div>${s}</div>`);
});
a div {
  color: red;
}
<h3 class="blog-post-title">
<a href="https://www.link1.com" class="blog-post-title-link">John Doe, MD</a>
</h3>

<h3 class="blog-post-title">
<a href="https://www.link2.com" class="blog-post-title-link">Jane Doe, MD</a>
</h3>

<h3 class="blog-post-title">
<a href="https://www.link3.com" class="blog-post-title-link">Jane Doe Smith, MD</a>
</h3>

Here’s the jQuery equivalent:

$('.blog-post-title-link').html((_, html) => 
  html.replace(/,(.+)/, (_, s) => `<div>${s}</div>`)
);

$('.blog-post-title-link').html((_, html) => 
  html.replace(/,(.+)/, (_, s) => `<div>${s}</div>`)
);
.blog-post-title div {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class="blog-post-title">
<a href="https://www.link1.com" class="blog-post-title-link">John Doe, MD</a>
</h3>

<h3 class="blog-post-title">
<a href="https://www.link2.com" class="blog-post-title-link">Jane Doe, MD</a>
</h3>

<h3 class="blog-post-title">
<a href="https://www.link3.com" class="blog-post-title-link">Jane Doe Smith, MD</a>
</h3>
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement