4

I need to change (just) the h3 tag to h2, keeping all default html elements inside, this code are erasing all html contents !!

<script type="text/javascript">
$(function () {
        $('.sideMenu h3').replaceWith(function () {
        return "<h2>" + $(this).text() + "</h2>";
    });
});
</script>

<div class="sideMenu">
    <h3 class="sapanos">
       <span></span>
       <a href="#" title="Sainos">Sapanos</a>
    </h3>
</div>
DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105
user2087563
  • 41
  • 1
  • 1
  • 2

2 Answers2

7

Use .html() to keep all the HTML structure. text() just gets the plain text, and throws away all the tags.

$('.sideMenu h3').replaceWith(function () {
  return "<h2>" + $(this).html() + "</h2>";
});

To keep the classes, do:

$('.sideMenu h3').replaceWith(function() {
  return $("<h2>", {
    class: this.className,
    html: $(this).html()
  });
});

John Brunner
  • 2,842
  • 11
  • 44
  • 85
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Now i need to change h2 to h3, keeping the h2 class and html elements. eg.

    html elements

    to

    html elements

    TNKS !!!!!!!
    – user2087563 May 07 '15 at 19:26
  • It's the exact same thing, just interchange the tags. What's the problem? – Barmar May 07 '15 at 19:33
  • My system is creating the h2 classes automatically, I do not have manual access to this html classes. eg:

    h2>

    h2>

    h2> the classes are diferent...

    – user2087563 May 07 '15 at 19:45
  • Oh, you're asking how to keep the class when you change the element type? – Barmar May 07 '15 at 19:47
  • Ok!! i got it !!! My code: $('.smartMenuAdded h3:eq(0)').replaceWith(function () { return '
    ' + $(this).html() + '
    '; });
    – user2087563 May 07 '15 at 21:19
  • Now i need remove ( language="javascript" ) from javas called on head. to . How can i do that ? TNKS !!!!! – user2087563 May 11 '15 at 18:16
  • What does that have to do with this question? If you have a different question, post it separately. And why do you need to do that? – Barmar May 11 '15 at 19:38
0

The problem is in

return "<h2>" + $(this).text() + "</h2>";

Instead of .text(), use .html().

.text() gets just the plain text content.

.html() gets the html content, which is what you want to transfer over.

Mar
  • 7,765
  • 9
  • 48
  • 82