how to change h2 to h1 via jquery

5

I need to change h2 to h1 dynamically I thought I would use jquery as follows but it does not work:

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


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

using classes as selector;

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

Any ideas?

    
asked by anonymous 21.07.2017 / 15:47

2 answers

6

This can be done using the replaceWith function, here's 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>H2spanola</span></h2>

*Notethatyouaretryingtoworkwithattributes(attr)andboth<h1>and<h2>are tags tags used to define HTML headers.

Update : Based on on this question from SOen , I discovered an interesting way to get the same result, the snippet follows:

$('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>H2spanola</span></h2>

Icomparedtheperformanceofthetwothrough jsperf and found that the first solution using the replaceWith function is more efficient.

Follow the test link you made: JsPerf - Replace Tag .

    
21.07.2017 / 15:52
1

You can also do this 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><h2class="titulo">Título</h2>
<input type="button" id="botaoAlterarTag" value="Alterar título">

Note that clicking the button causes% of the text in question to go from tag to h2 and then a h1 is given in refresh that has tag named ' title 'using the class method of jQuery to display the text with the new load() . This example made with the event tag , but you can use another event according to your need.

    
21.07.2017 / 17:48