Solution 1 :

With JQuery it will look like this:

var nestedSpan = $('#4 span:first');
var nestedSpanText = nestedSpan.text();
nestedSpan.replaceWith('<div>' + nestedSpanText + '</div>');

But imao it is very bad idea to name id page anchor as number.

Your solution also was not so bad. Just needed better selector:

var nestedSpan = $('#4 span:first');

nestedSpan.replaceWith(function() {
    return '<div>'+$(this).html()+'</div>';
});

Solution 2 :

Span may not contain a div (which I why you want to change it?

Also I would never use a numeric ID

Try this

$("#Span4").replaceWith(function() {
  return $("<div/>", {
    "style": this.getAttribute("style"),
    "id": this.id
  }).html($(this).html());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="Span4" style="display: block">
  <div>
    <span>ttttttt</span>
    <p>ttttttt</p>
  </div>
</span>

Solution 3 :

$('#4 div').unwrap().wrap('<div id="4" style="display: block;"></div>');
$('#4 div').unwrap().wrap('<div id="4" style="display: block;"></div>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="4" style="display: block">
  <div>
    <span>ttttttt</span>
    <p>ttttttt</p>
  </div>
</span>

Problem :

I have a html element:

<span id="4" style="display: block">
  <div>
    <span>ttttttt</span>
    <p>ttttttt</p>
  </div>
</span>

I want to change the outermost span to div, so it looks like:

<div id="4" style="display: block">
  <div>
    <span>ttttttt</span>
    <p>ttttttt</p>
  </div>
</div>

I checked online and find a solution:

var myNodes = $('[type="type1"]')

myNodes[0].replaceWith(function() {
return '<div>'+$(this).html()+'</div>';
});

However, it does not work. Screenshot below:

enter image description here

Can I get some help?

enter image description here

Comments

Comment posted by GrafiCode

in order to use

Comment posted by Carsten Løvbo Andersen

if we overlook the fact that an element’s id should not start with a number then it would be

Comment posted by kevinzf

Thanks! I used var myNodes = $(‘[type=”type1″]’) to select nodes.

Comment posted by Calvin Nunes

why do you think that

Comment posted by GrafiCode

@CarstenLøvboAndersen numeric IDs are not forbidden in html5 🙂

Comment posted by Mikita Melnikau

When we change tag by this code we: 1. copy nested html 2. destroy old tag 3. create new tag on it place. 4. place inner html back. So if you want more operations with this element you need reselect it. I suggest you to set custom

By