Answer the question
In order to leave comments, you need to log in
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();
}
});
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question