Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the tag but keep the attributes and content -- jQuery/Javascript

<a href="page.html" class="class1 class2" id="thisid">Text</a>

changed to

<p href="page.html" class="class1 class2" id="thisid">Text</p>

I'm familiar with jQuery's replaceWith but that doesn't keep attributes/content as far as I know.

Note: Why would p have a href? Cuz I need to change p back to a on another event.

like image 306
Kyle Cureau Avatar asked Sep 08 '10 08:09

Kyle Cureau


People also ask

How to change attr value in jQuery?

jQuery attr() Method When this method is used to return the attribute value, it returns the value of the FIRST matched element. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.

How do I change a tag in JavaScript?

To change the element tag name in JavaScript, simply need to make a new element and move over all the elements so you keep onclick handlers and such, and then replace the original thing.

How to add attribute jQuery?

You can add attributes using attr like so: $('#someid'). attr('name', 'value'); However, for DOM properties like checked , disabled and readonly , the proper way to do this (as of JQuery 1.6) is to use prop .

How JavaScript can change HTML attribute values?

To change the attribute value of an HTML element HTML DOM provides two methods which are getAttribute() and setAttribute(). The getAttribute() is used to extract the current value of the attribute while setAttribute() is used to alter the value of the attribute.


1 Answers

It's better to create jQuery plugin for future re-usability:

(function (a) {
    a.fn.replaceTagName = function (f) {
        var g = [],
            h = this.length;
        while (h--) {
            var k = document.createElement(f),
                b = this[h],
                d = b.attributes;
            for (var c = d.length - 1; c >= 0; c--) {
                var j = d[c];
                k.setAttribute(j.name, j.value)
            }
            k.innerHTML = b.innerHTML;
            a(b).after(k).remove();
            g[h - 1] = k
        }
        return a(g)
    }
})(window.jQuery);

Usage:

// Replace given object tag's name
$('a').replaceTagName("p");

Example: JSFiddle

like image 185
Ilia Avatar answered Sep 20 '22 06:09

Ilia