1

I want to change an element tag but without losing the element's attributes.

This is the element:

<h4 class="form-title ng-binding" id="s50" ng-bind-html="'s50' | translate" translate-cloak="s50">searching</h4>

I want to change h4 to h1 so it will look like this:

<h1 class="form-title ng-binding" id="s50" ng-bind-html="'s50' | translate" translate-cloak="s50">searching</h1>

I've tried the code:

$('h4').replaceWith($('<h1>' + this.innerHTML + '</h1'));

but in this way I'm losing the attributes this.innerHTML returns undefined I've tried to change this.inner.HTML to $('h4').innerHTML and still it returns undefined.

Scimonster
  • 32,893
  • 9
  • 77
  • 89
barak
  • 147
  • 1
  • 3
  • 17
  • What about using and changing the css instead of the tag? – John Mar 27 '16 at 11:33
  • Are you losing attributes in all browsers or only in Internet Explorer? – Technoh Mar 27 '16 at 11:39
  • I need this tag to be h1 and I can't touch this website code, I only give this website a service with my own script and I need to add a code to my script that change this h4 tag to h1 tag. – barak Mar 27 '16 at 11:41
  • @barak It's better to create a plugin, so you could use it later: http://stackoverflow.com/a/36247124/1455661 – Ilia Ross Mar 27 '16 at 12:08

4 Answers4

3

The first thing you need to do is get all the attributes. Might as well get the innerHTML while your here too.

var $h4 = $('h4');
var attrs = $h4[0].attributes;
var html = $h4[0].innerHTML;

attrs is now an array of attributes, you'll want it to look like an object so you can pass it into the .attr() method.

var attr = {};
$.each(attrs, function(i,e) { attr[e.nodeName] = e.nodeValue; });
var $h1 = $('<h1/>').html(html).attr(attr);
$h4.replaceWith($h1);
Donnie D'Amato
  • 3,832
  • 1
  • 15
  • 40
1

You can get all the attributes one by one by using attr method and pass them to new h1 element.

var $h4 = $('h4#s50');
var h4bind = $h4.attr('ng-bind-html');
var h4class = $h4.attr('class');
var h4id = $h4.attr('id');
var h4tc = $h4.attr('translate-cloak');
var h4text = $h4.text();

$h4.replaceWith('<h1 ng-bind-html="'+ h4bind +'" class="'+ h4class +'" id="'+ h4id+'" translate-cloak="'+h4tc+ '">'+ h4text +'</h1>');

Here is the solution: https://jsfiddle.net/h2jfu0e8/

Kaan Burak Sener
  • 974
  • 10
  • 19
0
$( document ).ready(function() {
   $('h4').replaceWith('<h1>' + document.querySelector("h4").innerHTML + '</h1>');
});
Nadimul De Cj
  • 484
  • 4
  • 16
0

Really depends on what you want to do with the elements in the end. If you just want to clone the element with the state of that time, the jQuery clone() method can be helpful to save some code. For more information see: https://api.jquery.com/clone/

Crix
  • 86
  • 3