Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery change tag

I have this code that doesn't work, can you help me? I want that I changed tag name "p" of class="s7" to "h1"

<script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
           $(".s7").replaceWith($('<h1>' + $(this).html() + '</h1>');
        });
    </script>
like image 907
Irakli Avatar asked Dec 21 '22 09:12

Irakli


2 Answers

The problem is that you're matching all the elements with class s7, but you need to process them one by one in order to copy their content into new elements. In your current code, this is always document, not the current element.

You can use each() to iterate over the matched elements:

$(".s7").each(function() {
    var $this = $(this);
    $this.replaceWith($("<h1>" + $this.html() + "</h1>"));
});

Or maybe:

$(".s7").each(function() {
    $("<h1>" + $(this).html() + "</h1>").replaceAll(this);
});
like image 193
Frédéric Hamidi Avatar answered Dec 24 '22 00:12

Frédéric Hamidi


You're missing a closing parenthesis, and you're using this in the wrong context:

$(document).ready(function(){
    $(".s7").replaceWith($('<h1>' + $(".s7").html() + '</h1>'));
});

http://jsfiddle.net/L82PW/

If you have multiple elements with a class name of s7, use .each():

$(document).ready(function(){
    $(".s7").each(function(){
        $(this).replaceWith($('<h1>' + $(this).html() + '</h1>'));
    });
});
like image 34
Joseph Silber Avatar answered Dec 24 '22 01:12

Joseph Silber