如何保留首个<h1>标签,将其余<h1>替换为<h2>标签?
保留首个
,将其余
替换为
的解决方案
你现有代码的问题有两个:一是选择器写反了,.section-title h1是查找class为section-title的元素内部的<h1>,但你的<h1>本身就带有这个类,应该用h1.section-title;二是没有做索引判断,导致所有<h1>都被替换了。
修正方案一:基于原有代码修改
在循环里判断元素索引,仅处理索引大于0的元素(即除第一个之外的所有<h1>):
$(document).ready(function () { $('h1.section-title').each(function (i, el) { // 索引从0开始,i>0对应除第一个外的所有元素 if (i > 0) { var className = $(el).attr("class"); $(el).replaceWith('<h2 class="' + className + '">' + $(el).html() + '</h2>'); } }); });
修正方案二:更简洁的写法
用jQuery的:gt(0)选择器直接选中索引大于0的元素(跳过第一个<h1>),结合回调函数生成新元素:
$(document).ready(function () { $('h1.section-title:gt(0)').replaceWith(function() { return $('<h2>', { class: this.className, html: $(this).html() }); }); });
替换后的效果
你的示例HTML会被修改为:
<h1 class="section-title"></h1> <h2 class="section-title"></h2> <h2 class="section-title"></h2> <h2 class="section-title"></h2> <h2 class="section-title"></h2>
内容的提问来源于stack exchange,提问作者Tausif Ahmad
相关产品推荐
相关产品推荐

