I want to replace all "i" elements with "span" elements.
I try many things but it didn’t work.
I didn’t find either error messages and debug JavaScript code in my browser.
I want to replace for example:
<i class="icon-user"></i>
to
<span class="icon-user"></span>
I try those but nothing works:
1)
(function($) {
$(document).ready(function() {
// Replace <i> elements with <span> elements
$('i.icon-user').replaceWith('<span class="icon-user"></span>');
});
})(jQuery);
2)
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>');
});
});
3)
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);
});
});
2
Answers
Here’s an approach utilizing regex to replace the tag name but keep its structure
Not using JQuery, using
Element.replaceWith
may be an idea. Here’s an example.