I'm using this [previously answered question](https://stackoverflow.com/questions/3665820/change-the-tag-but-keep-the-attributes-and-content-jquery-javascript "this previously answered question") about altering an HTML tag and while trying to update some HTML tags, I'm having trouble reaching the tags within a parent of the same tag.

For example, updating a span to a div should result in:

```
<div>
    <div>div within a div</div>
</div>

```

But is showing up like:

```
<div>
    <span>div within a div</span>
</div>

```

And for reference, this is the js:

```
var divTag = 'div';

$('span').each(function() {
    var outer = this.outerHTML;

    // Replace all span tags with the type of divTag
    var regex = new RegExp('<' + this.tagName, 'i');
    var newTag = outer.replace(regex, '<' + divTag);

    // Replace closing tag
    regex = new RegExp('</' + this.tagName + '>$', 'i');
    newTag = newTag.replace(regex, '</' + divTag + '>');

    $(this).replaceWith(newTag);
});

```

Any help is greatly appreciated! Thanks!