come cambiare un tipo di elemento usando jquery


Risposte:


137

Ecco un modo per farlo con jQuery:

var attrs = { };

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


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

Esempio: http://jsfiddle.net/yapHk/

Aggiorna , ecco un 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);

Esempio: http://jsfiddle.net/mmNNJ/


2
@FelixKling: Grazie, childrennon ha funzionato ma contentsha funzionato.
Andrew Whitaker

1
@Andrew Whitaker WOW !!! sei bravo! Quindi, per essere sicuro di usare b.class o b.xyzxterms (xyzxterms è il nome della classe)
bammab

5
@AndrewWhitaker: Se non sbaglio, nel tuo plugin, gli attributi del primo elemento corrispondente verranno applicati a tutti gli elementi corrispondenti. Non è necessariamente quello che vogliamo. Inoltre viene generato un errore quando non ci sono elementi corrispondenti nel set. Ecco una versione modificata del tuo plugin che mantiene i propri attributi per ogni elemento abbinato e non attiva un errore su un set vuoto: gist.github.com/2934516
Etienne

2
Funziona a meraviglia! Tranne che quando il selettore non riesce a trovare alcun elemento corrispondente, lancia un messaggio di errore alla console perché questo [0] è undefined che accede alle interruzioni degli attributi. L'aggiunta di una condizione lo risolve: if (this.length! = 0) {...
ciuncan

1
@ciuncan: grazie per il feedback! Dovrebbe davvero essere racchiuso in un .eachblocco come mostra anche una risposta sotto.
Andrew Whitaker

14

Non sono sicuro di jQuery. Con JavaScript semplice potresti fare:

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

Non sono sicuro di quanto sia compatibile con il browser incrociato.

Una variazione potrebbe essere:

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

Per ulteriori informazioni, vedere Node.attributes [MDN] .


Le prestazioni del tuo codice sono migliori del "puro jQuery" (es. Codice di Andrew), ma hai un piccolo problema con i tag interni, vedi il corsivo in questo esempio con il tuo codice e l' esempio di riferimento .
Peter Krauss

Se si corregge, è possibile definire un "plugin jquery ideale" , chiamando la funzione dal jquery-plugin-template.
Peter Krauss

Fisso. Il problema era che dopo la copia sul primo figlio, non ha più un fratello successivo, quindi while(child = child.nextSibling)non è riuscito. Grazie!
Felix Kling

9

@jakov e @Andrew Whitaker

Ecco un ulteriore miglioramento in modo che possa gestire più elementi contemporaneamente.

$.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);
};

3

La risposta di @ Jazzbo ha restituito un oggetto jQuery contenente un array di oggetti jQuery, che non era concatenabile. L'ho modificato in modo che restituisca un oggetto più simile a quello che $ .each avrebbe restituito:

    $.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);
    };

(Ha anche fatto un po 'di pulizia del codice in modo che passi jslint.)


Questa sembra l'opzione più carina. L'unica cosa che non capisco è perché hai spostato la dichiarazione var per attrs da this.each (). Funziona bene se lasciato lì: jsfiddle.net/9c0k82sr/1
Jacob C. dice

Ho raggruppato le variabili a causa di jslint: "(Ho anche fatto un po 'di pulizia del codice in modo che passi jslint.)". L'idea alla base di tutto ciò è rendere il codice più veloce, penso (non dover dichiarare nuovamente le variabili all'interno di ogni eachciclo).
fiskhandlarn

2

L'unico modo che mi viene in mente è copiare tutto manualmente: esempio 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);
});

2

@Andrew Whitaker: propongo questa modifica:

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

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

    var newelement = $("<" + newType + "/>", attrs).append($(this).contents());
    this.replaceWith(newelement);
    return newelement;
};

Quindi puoi fare cose come: $('<div>blah</div>').changeElementType('pre').addClass('myclass');


2

Mi piace l'idea di @AndrewWhitaker e altri di utilizzare un plugin jQuery - per aggiungere il file changeElementType() metodo. Ma un plugin è come una scatola nera, non importa il codice, se è piccolo e funziona bene ... Quindi, le prestazioni sono necessarie ed è più importante del codice.

"Pure javascript" ha prestazioni migliori di jQuery: penso che il codice di @ FelixKling abbia prestazioni migliori di @ AndrewWhitaker e altri.


Qui un codice "puro Javavascript" (e "puro DOM"), incapsulato in un plugin jQuery :

 (function($) {  // @FelixKling's code
    $.fn.changeElementType = function(newType) {
      for (var k=0;k<this.length; k++) {
       var e = this[k];
       var new_element = document.createElement(newType),
        old_attributes = e.attributes,
        new_attributes = new_element.attributes,
        child = e.firstChild;
       for(var i = 0, len = old_attributes.length; i < len; i++) {
        new_attributes.setNamedItem(old_attributes.item(i).cloneNode());
       }
       do {
        new_element.appendChild(e.firstChild);
       }
       while(e.firstChild);
       e.parentNode.replaceChild(new_element, e);
      }
      return this; // for chain... $(this)?  not working with multiple 
    }
 })(jQuery);

2

Ecco un metodo che utilizzo per sostituire i tag html in jquery:

// Iterate over each element and replace the tag while maintaining attributes
$('b.xyzxterms').each(function() {

  // Create a new element and assign it attributes from the current element
  var NewElement = $("<h1 />");
  $.each(this.attributes, function(i, attrib){
    $(NewElement).attr(attrib.name, attrib.value);
  });

  // Replace the current element with the new one and carry over the contents
  $(this).replaceWith(function () {
    return $(NewElement).append($(this).contents());
  });

});

2

Con jQuery senza iterare sugli attributi:

Il replaceElemmetodo seguito accetta old Tag, new Tage contexted esegue la sostituzione con successo:


replaceElem('h2', 'h1', '#test');

function replaceElem(oldElem, newElem, ctx) {
  oldElems = $(oldElem, ctx);
  //
  $.each(oldElems, function(idx, el) {
    var outerHTML, newOuterHTML, regexOpeningTag, regexClosingTag, tagName;
    // create RegExp dynamically for opening and closing tags
    tagName = $(el).get(0).tagName;
    regexOpeningTag = new RegExp('^<' + tagName, 'i'); 
    regexClosingTag = new RegExp(tagName + '>$', 'i');
    // fetch the outer elem with vanilla JS,
    outerHTML = el.outerHTML;
    // start replacing opening tag
    newOuterHTML = outerHTML.replace(regexOpeningTag, '<' + newElem);
    // continue replacing closing tag
    newOuterHTML = newOuterHTML.replace(regexClosingTag, newElem + '>');
    // replace the old elem with the new elem-string
    $(el).replaceWith(newOuterHTML);
  });

}
h1 {
  color: white;
  background-color: blue;
  position: relative;
}

h1:before {
  content: 'this is h1';
  position: absolute;
  top: 0;
  left: 50%;
  font-size: 5px;
  background-color: black;
  color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="test">
  <h2>Foo</h2>
  <h2>Bar</h2>
</div>

In bocca al lupo...


1
Mi piace la tua risposta! Perché? Perché TUTTE le altre risposte falliranno nel tentativo di fare qualcosa di semplice come convertire un'ancora in un'etichetta. Detto questo, considera le seguenti correzioni / revisioni alla tua risposta: A). Il tuo codice non funzionerà con i selettori. B) Il tuo codice deve eseguire regex senza distinzione tra maiuscole e minuscole. Detto questo, ecco le mie soluzioni suggerite: regexOpeningTag = new RegExp ('^ <' + $ (el) .get (0) .tagName, 'i'); regexClosingTag = new RegExp ($ (el) .get (0) .tagName + '> $', 'i');
zax

La sostituzione del semplice HTML in questo modo ti farà anche perdere tutti i listener di eventi collegati agli oggetti.
José Yánez

1

Soluzione Javascript

Copia gli attributi del vecchio elemento nel nuovo elemento

const $oldElem = document.querySelector('.old')
const $newElem = document.createElement('div')

Array.from($oldElem.attributes).map(a => {
  $newElem.setAttribute(a.name, a.value)
})

Sostituisci il vecchio elemento con il nuovo elemento

$oldElem.parentNode.replaceChild($newElem, $oldElem)

mapcrea un nuovo array inutilizzato, potrebbe essere sostituito da forEach.
Orkhan Alikhanov

1

Ecco la mia versione. È fondamentalmente la versione di @ fiskhandlarn, ma invece di costruire un nuovo oggetto jQuery, sovrascrive semplicemente i vecchi elementi con quelli appena creati, quindi non è necessaria alcuna fusione.
Demo: http://jsfiddle.net/0qa7wL1b/

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

  this.each( function( index ){

    var atts = {};
    $.each( this.attributes, function(){
      atts[ this.name ] = this.value;
    });

    var $old = $(this);
    var $new = $('<'+ newType +'/>', atts ).append( $old.contents() );
    $old.replaceWith( $new );

    $this[ index ] = $new[0];
  });

  return this;
};
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.