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);
<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(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)
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>
Here's an approach utilizing regex to replace the tag name but keep its structure