Cristi
Cristi

Reputation: 49

Add class to a text row with JS or jQuery

I have this text generated by a WordPress plugin that is put up in a single div. See the Example below. No p tags nothing. Is there a way to add some HTML tags per row so I can style them properly?

<div class="am-event-modal__description">Lorem ipsum, or lipsum as it is sometimes known,

Lorem ipsum, or lipsum as it is sometimes known,
Lorem ipsum, or lipsum as it is sometimes known,

Dates: 
april 1
aprili 2
april 3
april 4</div>

Thank you!

Upvotes: 0

Views: 50

Answers (1)

n--
n--

Reputation: 3856

you can split the text by new lines, then put every line in a p element like this:

const div = document.querySelector('.am-event-modal__description');
const doc = document.createDocumentFragment();
div.childNodes.forEach(el => {
  if (el.nodeType !== Node.TEXT_NODE) {
    doc.appendChild(el);
    return;
  }
  el.textContent.split('\n').forEach(line => {
    const p = document.createElement('p');
    p.textContent = line;
    doc.appendChild(p);
  });
});
div.textContent = '';
div.appendChild(doc);
<div class="am-event-modal__description">Lorem ipsum, or lipsum as it is sometimes known,

Lorem ipsum, or lipsum as it is sometimes known,
Lorem ipsum, or lipsum as it is sometimes known,

Dates: 
april 1
aprili 2
april 3
april 4</div>

Upvotes: 2

Related Questions