求助:如何将<i>元素替换为<span>元素?多种方案均无效
将页面所有
<i>元素替换为<span>元素的解决方案 需求:把页面中所有<i>元素替换为<span>元素,例如<i class="icon-user"></i>替换为<span class="icon-user"></span>,尝试多种方法无效且无报错信息。
已尝试的三种方案
方案1(jQuery)
(function($) { $(document).ready(function() { // Replace <i> elements with <span> elements $('i.icon-user').replaceWith('<span class="icon-user"></span>'); }); })(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <p>This is an icon <i class="icon-user"></i> and this as well <i class="icon-user"></i> </p>
方案2(带检查的jQuery)
jQuery(document).ready(function($) { // Check if jQuery is loaded if (typeof jQuery === 'undefined') { console.error('jQuery is not loaded.'); return; } // Check if the element exists if ($('i.icon-user').length === 0) { console.error('The element with class "icon-user" does not exist.'); return; } // Replace <i> with <span> $('i.icon-user').each(function() { $(this).replaceWith('<span class="icon-user"></span>'); }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js" integrity="sha512-v2CJ7UaYy4JwqLDIrZUI/4hqeoQieOmAZNXBeQyjo21dadnwR+8ZaIJVT8EE2iyI61OV8e6M8PP2/4hpQINQ/g==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <p>This is an icon <i class="icon-user"></i> and this as well <i class="icon-user"></i> </p>
方案3(原生JS)
document.addEventListener('DOMContentLoaded', function() { var iconUsers = document.querySelectorAll('i.icon-user'); iconUsers.forEach(function(iconUser) { var spanElement = document.createElement('span'); spanElement.className = 'icon-user'; iconUser.parentNode.replaceChild(spanElement, iconUser); }); });
<p>This is an icon <i class="icon-user"></i> and this as well <i class="icon-user"></i> </p>
可行解决方法
1. 处理动态加载的元素(最可能的失效原因)
如果<i>元素是页面加载后通过JS动态生成的,DOMContentLoaded或$(document).ready会在元素生成前执行,导致无法匹配。可以用MutationObserver监听DOM变化,确保捕获所有新增的目标元素:
// 替换函数:将<i>转为<span>,保留所有属性和内容 function replaceIcon(icon) { const span = document.createElement('span'); // 复制所有属性 Array.from(icon.attributes).forEach(attr => { span.setAttribute(attr.name, attr.value); }); // 复制所有子节点(文本、嵌套元素等) while (icon.firstChild) { span.appendChild(icon.firstChild); } icon.parentNode.replaceChild(span, icon); } // 初始执行,替换页面已存在的元素 document.querySelectorAll('i.icon-user').forEach(replaceIcon); // 监听DOM变化,捕获新增的<i>元素 const observer = new MutationObserver((mutations) => { mutations.forEach((mutation) => { if (mutation.addedNodes.length) { mutation.addedNodes.forEach(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查当前节点是否是目标元素 if (node.tagName === 'I' && node.classList.contains('icon-user')) { replaceIcon(node); } // 递归查找子节点中的目标元素 const icons = node.querySelectorAll('i.icon-user'); icons.forEach(replaceIcon); } }); } }); }); // 启动监听,覆盖整个文档的子节点变化 observer.observe(document.body, { childList: true, subtree: true });
2. 简化延迟执行方案(适合快速测试)
如果不想用Observer,可以通过延迟执行确保元素已生成:
setTimeout(() => { document.querySelectorAll('i.icon-user').forEach(icon => { const span = document.createElement('span'); // 复制所有属性和内容 Array.from(icon.attributes).forEach(attr => span.setAttribute(attr.name, attr.value)); while (icon.firstChild) span.appendChild(icon.firstChild); icon.parentNode.replaceChild(span, icon); }); }, 1000); // 延迟时间可根据实际加载情况调整
3. 全局替换所有<i>元素(不限定class)
如果需要替换所有<i>元素,只需把选择器改为document.querySelectorAll('i'),替换函数逻辑保持不变即可。
内容的提问来源于stack exchange,提问作者Michail Kappas
相关产品推荐
相关产品推荐

