Replace <span> tag with <div> tag using jQuery

In this post I am going to explain, how we can replace the tag with a

tag using jQuery. Here the tag &

tag I am using is just for the demo, there’s nothing special about these tags. You can replace it with any HTML tag you like. Let’s say we have HTML markup like this:

<div id="parent2" class="parent">
     <span>
         <b>This is sample text 1</b>
     </span>
     <span>
         <i>This is sample text 2</i>
     </span>
</div>

And now we have a requirement, where we need to replace all the  tag with a 

tag. So, our desired result is something like this:

<div id="parent2" class="parent">
     <div class="myClass">
         <b>This is sample text 1</b>
     </div>
     <div class="myClass">
         <i>This is sample text 2</i>
     </div>
</div>

Now, we can achieve this using jQuery like this:

var $span = $("#parent2 span");
$span.replaceWith(function () {
    return $('<div/>', {
        class: 'myClass',
        html: this.innerHTML
    });
});

Explanation:

  1. Code in the first line
    var $span = $("#parent2 span");
    

    Now the above code is used to get all the span’s inside the div element with the id as `parent2`.

  2. Code in the second line
    $span.replaceWith(function () {
    

    In the above code we are using here the replaceWith( function ). The replaceWith() method here takes a function as its argument and it removes content from the DOM and inserts new content in its place with a single call. Here, we want to remove the from the DOM.

  3. Code in the third line
    return $('<div/>', {
    

    This code will return a new

    as a return value to the replaceWith() function, which is used to replace the . The code in next few lines are used set a new class and the html to the new created

    .

Demo:
Working Demo on jsFiddle

Note:
The main thing to notice here is that, here we have replaced the <span> tag with a <div> tag in the above example, but the same can be used to replace any HTML tag with an another tag using the above jQuery code, with little modification of course 😉

If you have any comments or suggestion or any queries about this post please add it in comments section. I would really appreciate it.

Happy Coding 🙂

8 thoughts on “Replace <span> tag with <div> tag using jQuery

  1. Hello! I really liked your forum, especially this section. I just signed up and immediately decided to introduce myself, if I’m wrong section, ask the moderators to move the topic to the right place, hopefully it will take me well… My name is Jack, me 34 years, humourist and serious man in one person. Ssory for my English.

  2. hi
    what about if I want to change a select option tag with unordered list I’ve tried this but did work

    one
    two
    three

    var $select = $(“#parent3 select”);
    $select.replaceWith(function () {
    return $(‘ ‘);
    });

    thanks

Leave a reply to Roosevelt Davis Cancel reply