S
S
Shimpanze2018-02-04 12:08:40
JavaScript
Shimpanze, 2018-02-04 12:08:40

JavaScript: how was this code written by professionals?

Good afternoon!
Wrote a snippet that replaces paragraphs with three asterisks (such as separators) with a <hr>.
How would this code be written by professionals?

// ищем все парараграфы
document.querySelectorAll('.entry-content p').forEach(function(entry) {
  // проверяем, подходит ли содержимое текущего параграфа в цикле
  // под наше условие (содержит ли только звездочки)
  if (entry.innerHTML == entry.innerHTML.match(/[\s]*\*[\s]*\*[\s]*\*[\s]*[\s]*/gi)) {
    // если да, вставляем после него элемент <hr>
    entry.insertAdjacentHTML('afterEnd', '<hr>');
    // и удаляем родительский элемент параграфа (как сделать умнее не придумал...)
    entry.closest("p").remove();
  }
});

Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2018-02-04
@Shimpanze

I'm not talking about, I would do this :

function replaceStars(collection) {
  var i, el, re = /^(\s*\*\s*){3}$/;
  for(i = 0; i<collection.length; i++) {
    el = collection[i];
    if( el.innerHTML.match(re)) {
      el.insertAdjacentHTML('afterend', '<hr>');
      el.parentNode.removeChild(el);
    }
  }
}

replaceStars(document.querySelectorAll('.entry-content p'));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question