how to change an element type using jquery

jquery replace element
jquery replace text in div
jquery change div content dynamically
jquery text replace
replace class jquery
jquery replacewith not working
change element type jquery
jquery find and replace html

I have the the following code

<b class="xyzxterms" style="cursor: default; ">bryant keil bio</b>

How would I replace the b tag to a h1 tag but keep all other attributes and information?

Here's one way you could do it with jQuery:

var attrs = { };

$.each($("b")[0].attributes, function(idx, attr) {
    attrs[attr.nodeName] = attr.nodeValue;
});


$("b").replaceWith(function () {
    return $("<h1 />", attrs).append($(this).contents());
});

Example: http://jsfiddle.net/yapHk/

Update, here's a plugin:

(function($) {
    $.fn.changeElementType = function(newType) {
        var attrs = {};

        $.each(this[0].attributes, function(idx, attr) {
            attrs[attr.nodeName] = attr.nodeValue;
        });

        this.replaceWith(function() {
            return $("<" + newType + "/>", attrs).append($(this).contents());
        });
    };
})(jQuery);

Example: http://jsfiddle.net/mmNNJ/

.replaceWith(), Description: Replace each element in the set of matched elements with the provided new May be an HTML string, DOM element, array of DOM elements, or jQuery object. version added: 1.4.replaceWith( function ). function. Type: Function(). You could add an ID to each element and then change the HTML with the html() or the text() function. But that seems like a lot of work. And it creates another problem if the HTML changes somewhere along the way. Another way is to loop through each of the list items and change them. jQuery has its own way to loop, called each().

Not sure about jQuery. With plain JavaScript you could do:

var new_element = document.createElement('h1'),
    old_attributes = element.attributes,
    new_attributes = new_element.attributes;

// copy attributes
for(var i = 0, len = old_attributes.length; i < len; i++) {
    new_attributes.setNamedItem(old_attributes.item(i).cloneNode());
}

// copy child nodes
do {
    new_element.appendChild(element.firstChild);
} 
while(element.firstChild);

// replace element
element.parentNode.replaceChild(new_element, element);

DEMO

Not sure how cross-browser compatible this is though.

A variation could be:

for(var i = 0, len = old_attributes.length; i < len; i++) {
    new_element.setAttribute(old_attributes[i].name, old_attributes[i].value);
}

For more information see Node.attributes [MDN].

Dynamically Change Element Type With jQuery , changeElementType is a simple yet useful jQuery plugin which allows the user to dynamically change the element type of  A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

@jakov and @Andrew Whitaker

Here is a further improvement so it can handle multiple elements at once.

$.fn.changeElementType = function(newType) {
    var newElements = [];

    $(this).each(function() {
        var attrs = {};

        $.each(this.attributes, function(idx, attr) {
            attrs[attr.nodeName] = attr.nodeValue;
        });

        var newElement = $("<" + newType + "/>", attrs).append($(this).contents());

        $(this).replaceWith(newElement);

        newElements.push(newElement);
    });

    return $(newElements);
};

How to change an HTML element name using jQuery, JQuery | Change an element type. </ title >. < script  The jQuery methods are used to change the element ID which are described below: jQuery attr() Method: This method set/return attributes and values of the selected elements. If this method is used to return the attribute value, it returns the value of first selected element.

@Jazzbo's answer returned a jQuery object containing an array of jQuery objects, which wasn't chainable. I've changed it so that it returns an object more similar to what $.each would have returned:

    $.fn.changeElementType = function (newType) {
        var newElements,
            attrs,
            newElement;

        this.each(function () {
            attrs = {};

            $.each(this.attributes, function () {
                attrs[this.nodeName] = this.nodeValue;
            });

            newElement = $("<" + newType + "/>", attrs).append($(this).contents());

            $(this).replaceWith(newElement);

            if (!newElements) {
                newElements = newElement;
            } else {
                $.merge(newElements, newElement);
            }
        });

        return $(newElements);
    };

(Also did some code cleanup so it passes jslint.)

Replace <span> tag with <div> tag using jQuery, Now the above code is used to get all the span's inside the div element with the id as `parent2`. Code in the second line. 1. $span.replaceWith(  Rather than change the type of tag, you should be changing the style of the tag (or rather, the tag with a specific id.) Its not a good practice to be changing the elements of your document to apply stylistic changes. Try this: Even in this case, you shouldn't be modifying your document structure.

Only way I can think of is to copy everything over manually: example jsfiddle

HTML

<b class="xyzxterms" style="cursor: default; ">bryant keil bio</b>

Jquery/Javascript

$(document).ready(function() {
    var me = $("b");
    var newMe = $("<h1>");
    for(var i=0; i<me[0].attributes.length; i++) {
        var myAttr = me[0].attributes[i].nodeName;
        var myAttrVal = me[0].attributes[i].nodeValue;
        newMe.attr(myAttr, myAttrVal);
    }
    newMe.html(me.html());
    me.replaceWith(newMe);
});

jQuery replaceWith() Method, Replace the first <p> element with new text: The replaceWith() method replaces selected elements with new content. HTML elements; jQuery objects The $(document).ready function is jQuery, and loads when the document has finished loading. This then changes the password field to a text field. Obviously you'll have to change 'password_field_id' to your password field's id.

jQuery Change Element Type usage: $("span").changeElementType , from Andrew Whitaker and Jazzbo, http://stackoverflow.com/a/15554920/161625. $.fn.changeElementType = function(newType) {. var newElements = [];. For example, if I am trying to load values into a drop-down list with jQuery, but the same script can generate code into a set of radio buttons, could I create something like: $('.trigger').live('click', function () { var elementType = $(this).prev().attr(WHAT IS IT); });

jQuery - Change Element type, <h1>jQuery</h1>. 4. <h3>Change Element Type</h3>. 5. </div>. 6. </header>. 7. ​. 8. <nav class="navbar navbar-default no-margin no-border no-radius">. 9. The following will return true if the element is an input: or you can use the following to get the name of the tag: Note, that using $("#elementId").is(":input") will generally tell you, if you're dealing with any kind of form element, without checking for its specific type (reference).

Selecting elements - Introduction to jQuery, jQuery lets you identify and select elements using a concept you may Once you select elements, you can then apply style rules to them, setting their font elements in CSS, including selecting by element type, class, and ID. You can simply use the jQuery prop() method to change the text of the buttons built using the HTML <input> element, whereas to change the text of the buttons which are created using the <button> element you can use the html() method.

Comments
  • See stackoverflow.com/questions/918792/…
  • @beanland: This does not keep the attributes.
  • @FelixKling: Thanks, children didn't work but contents did.
  • @Andrew Whitaker WOW!!! you're good! So just to be sure I use b.class or b.xyzxterms (xyzxterms being the name of the class)
  • @AndrewWhitaker: If I'm not wrong, in your plugin, the attributes of the first matched element will be applied to all matching elements. It's not necessarily what we want. Also an error is raise when there's not matched element in the set. Here's a modified version of your plugin that keep own attributes for each matched elements and do not trigger an error on empty set: gist.github.com/2934516
  • This works like a charm! Except that when the selector fails to find any matching element, it throws an error message to console because this[0] is undefined accessing attributes breaks. Adding a condition fixes it: if (this.length != 0) {...
  • @ciuncan: Thanks for the feedback! It should really be wrapped in an .each block like an answer below shows too.
  • The performance of your code is better than the "pure jQuery" (ex. Andrew's code), but have a little problem with inner tags, see italic at this example with your code and the reference-example.
  • If you correct, an "ideal jquery plugin" can be defined, calling your function by the jquery-plugin-template.
  • Fixed. The problem was that after the copying over the first child, it doesn't have a next sibling anymore, so while(child = child.nextSibling) failed. Thanks!
  • This seems like the nicest option. The only thing I don't get is why you moved the var declaration for attrs out of the this.each(). It works fine with it left there: jsfiddle.net/9c0k82sr/1
  • I grouped the vars because of jslint: "(Also did some code cleanup so it passes jslint.)". The idea behind that is to make the code faster, i think (not having to redeclare vars within each each loop).
  • I like your answer! Why? Because ALL of the other answers will fail in attempting to do something simple like convert an anchor to a label. That said, please consider the following fixes/revisions to your answer: A). Your code won't work with selectors. B) Your code needs to perform case insensitive regex. That said, here are my suggested fixes: regexOpeningTag = new RegExp('^<' + $(el).get(0).tagName, 'i'); regexClosingTag = new RegExp($(el).get(0).tagName + '>$', 'i');
  • Replacing plain HTML like this will also make you lose any event listeners attached to the objects.
  • map creates a new unused array, it could be replaced by forEach.