how to change the <H2> to <H1> via jquery

Asked

Viewed 408 times

5

I need to change H2 to H1 dynamically I thought to use jquery as follows but it doesn’t work:

$("h2").removeAttr("h2").attr('h1');


$("h2").attr('h1');

using classes as selector;

$(".wd-product-list .wd-widget .wd-title").Attr("h1");

Any idea?

2 answers

6


This can be done using the function replaceWith, follows an example:

$('h2').replaceWith(function() {
  return $("<h1>" + $(this).html() + "</h1>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>H2</h2>
<h2><span>H2 span ola</span></h2>

*Note that you are trying to work with attributes (attr) both the <h1> as to the <h2> sane tags used to define HTML headers.


Update: Based in that question of Soen, I found an interesting way to arrive at the same result, follow the snippet:

$('h2').contents().unwrap().wrap('<h1/>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>H2</h2>
<h2><span>H2 span ola</span></h2>

I compared the performance of the two through the jsperf and found that the first solution using the function replaceWith is more efficient.

Follow the link of the test performed: Jsperf - Replace Tag.

  • I understood that this was the reason that did not work. Following the logic I used there is no simpler way to do this? less code, just a question to increase my knowledge. And did not know the tags you used of jquery [replaceWith]. At first thank you

  • 1

    I didn’t know that jsPerf, very interesting.

  • @hyperpixel I believe that these forms are already framed in the group of simple solutions to this problem, for sure there are others, but it will not change much because the code is already well simplified.

  • @Isac I met not long ago too, in some response here from the same OS, it’s pretty cool.

1

You can also do as follows:

$('#botaoAlterarTag').click(function() {
  $('h2').contents().unwrap().wrap("<h1 class='titulo'>");
  $('.titulo').load();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h2 class="titulo">Título</h2>
<input type="button" id="botaoAlterarTag" value="Alterar título">

Note that when you click the button, the tag the text in question shall be replaced by h2 for h1 and then is given a refresh in tag who owns class called title by the method load() jQuery to display text with the new tag. This example I did with the event click, but you can use another event according to your need.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.