Как на странице заменить все заголовки h2-h6 на тег div с сохранением всех атрибутов и у которых есть класс title?
$('h2,h3,h4,h5,h6').each(function(i,el){
var $h = $(el);
console.log($h);
if($h.hasClass('title')){
$($h).replaceWith(function(index, oldHTML){
return $("<div />").html(oldHTML);
});
}
})
такой код не сохраняет атрибуты
P.S.
такое решение правильное?
$('h2,h3,h4,h5,h6').each(function(i,el){
var $h = $(el);
if($h.hasClass('title')){
var div = document.createElement('div'),
$div = $(div);
$.each($h[0].attributes, function(i,attr){
var a = attr.nodeName||attr.name;
var val = attr.nodeValue;
$div.attr(a, val);
});
$div.html($h.html());
$h.replaceWith($div);
}
})
$('h2,h3,h4,h5,h6').each(function(){
$(this).replaceWith(function(){
var $div = $('<div/>', { html: $(this).html() });
$.each(this.attributes, function(i, attribute) {
$div.attr(attribute.name, attribute.value);
});
return $div;
});
});
h1, h2, h3, h4, h5, h6 { background-color: red; }
div { background-color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>H1</h1>
<h2>H2</h2>
<h3>H3</h3>
<h4>H4</h4>
<h5>H5</h5>
<h6>H6</h6>
Апостиль в Лос-Анджелесе без лишних нервов и бумажной волокиты
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости