2010-09-08 13 views
6

textocambiar la etiqueta, pero mantener los atributos y el contenido - jQuery/Javascript

cambió a

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

Estoy familiarizado con jQuery de replaceWith pero eso no impide que los atributos/contenido de la medida de lo Lo sé.

Nota: ¿Por qué p tendría un href? Porque tengo que cambiar p de nuevo a a en otro evento.

+0

¿Por qué no acaba de leer los atributos (href, class e id) y luego reasignar después del reemplazo? – Vikash

Respuesta

0

probar esto:

var $a = $('a#thisid'); 
var ahref = $a.attr('href'); 
var aclass = $a.attr('class'); 
var aid = $a.attr('id'); 
var atext = $a.text(); 
$a.replaceWith('<p href="'+ ahref +'" class="'+ aclass +'" id="'+ aid+'">'+ atext +'</p>'); 
+0

¡increíble! ¡Gracias! – Kyle

2

hacky que hacer el truco

var p = $('a').wrapAll('<div class="replace"></div>'); 

var a = $('div').map(function(){ 
    return this.innerHTML; 
}).get().join(' '); 


$('div.replace').html(a.replace(/<a/g,'<p').replace(/a>/g,'p>')); 

demo

+0

+1 Gracias Reigel! Esto parece otra gran respuesta – Kyle

+0

+1 Buena idea, ¿Seguro que la bandera 'g' es necesaria en las expresiones? Supongo que solo debería hacerse un reemplazo, ¿eh? –

17

Aquí es un método más genérico:

// New type of the tag 
var replacementTag = 'p'; 

// Replace all a tags with the type of replacementTag 
$('a').each(function() { 
    var outer = this.outerHTML; 

    // Replace opening tag 
    var regex = new RegExp('<' + this.tagName, 'i'); 
    var newTag = outer.replace(regex, '<' + replacementTag); 

    // Replace closing tag 
    regex = new RegExp('</' + this.tagName, 'i'); 
    newTag = newTag.replace(regex, '</' + replacementTag); 

    $(this).replaceWith(newTag); 
}); 

Puede probar el código aquí: http://jsfiddle.net/tTAJM/

+0

¡genial! ¡gracias! – Kyle

+0

buena solución, pero me dieron un error cuando la etiqueta tiene otra igual en el interior: '' (Converto a '

'), que fija el cambio de "// Reemplazar etiqueta de cierre" sección para esto: 'expresiones regulares = nuevo RegExp (' $', 'i'); newTag = newTag.replace (regex, ''); ' –

4

Aquí es un método que utilizo para reemplazar las etiquetas HTML en jQuery:

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

    // Create a new element and assign it attributes from the current element 
    var NewElement = $("<p />"); 
    $.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()); 
    }); 

}); 

que habría también suelen limitar a una clase específica, como $('a.class1').each(function() para el ejemplo encima.

+0

Esto es excelente, Seth , el método más limpio y más fácil de implementar en mi opinión. – Nathan

2

Es mejor crear plugin de jQuery para la futura reutilización:

(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); 

Uso:

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

Ejemplo: JSFiddle

0

lo hice en uno Javascript llanura-función:

function ReplaceTags(Original, Replace){ 
    var oarr = document.getElementsByTagName(Original); 
    for(i=0; oarr.length < i; i++){ 
var html = oarr[i].outerHTML; 
oarr[i].outerHTML = (html.replace(Original, Replace)); 
    } 
} 

Si desea reemplazar sólo una etiqueta específica, simplemente eliminar el bucle for:

function ReplaceTag(Original, Replace, customi){ 
// If customi = 0 the first appearance will get replaced 
var i = customi; 
    if(i == undefined) 
    i=0; 
var oarr = document.getElementsByTagName(Original); 
var html = oarr[i].outerHTML; 
oarr[i].outerHTML = (html.replace(Original, Replace)); 

} 
Cuestiones relacionadas