skip to Main Content

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


  1. Here’s an approach utilizing regex to replace the tag name but keep its structure

    document.addEventListener('DOMContentLoaded', function() {
      document.querySelectorAll('i.icon-user').forEach(function(iconUser) {
        iconUser.outerHTML = iconUser.outerHTML.replace(/(?:(?<=^<)|(?=w+>$))bw+b/g, 'span')
      });
    
      console.log(document.body.innerHTML);
    });
    <i class="icon-user"></i>
    <div>
      <i id="foo" class="icon-user">
        <span>test</span>
      </i>
      <i class="bar"></i>
    </div>
    Login or Signup to reply.
  2. Not using JQuery, using Element.replaceWith may be an idea. Here’s an example.

    setTimeout(replaceIWithSpan, 1500);
    
    function replaceIWithSpan() {
      document.querySelectorAll(`.icon-user`)
      .forEach( i => {
        const span = document.createElement(`span`);
        for (const attr of i.attributes) {
          span.setAttribute(attr.name, attr.value);
        }
        span.innerHTML = i.innerHTML;
        i.replaceWith(span);
      });
    }
    span.icon-user {
      color: green;
      font-weight: bold;
    }
    <i class="icon-user">&lti>#1</i>
    <i class="icon-user">&lti>#2</i> 
    <i class="icon-user">&lti>#3</i> 
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search