2011-06-26 6 views
5

que tener algo como esto:Cambiar el nombre de la etiqueta, pero mantener todos los atributos

<span id="anId" someOtherAttributes....>test</span> 

que quiero cambiar en:

<a id="anId" theSameOtherAttributes...>test</a> 

Tengo dos preguntas:

  1. ¿Cómo puedo cambiar solo el nombre de la etiqueta?

    o

  2. ¿Cómo puedo copiar todos los atributos?

+1

http://stackoverflow.com/questions/918792/use-jquery-to-change-an -html-tag – Babiker

+1

parece que no tiene atributos sobre – Ben

Respuesta

0

No voy a codificar, sino para que la cabeza en la dirección correcta, la búsqueda de cómo construir una etiqueta en jQuery (algo así como http://api.jquery.com/append/)

Entonces bucle a través de cada etiqueta con algo como Iterating over element attributes with jQuery, y añada cada atributo a la etiqueta anexa.

EDIT: bien, aquí está un ejemplo: http://jsfiddle.net/mazzzzz/xUUn3/

+0

Cuando utilicé el.attributes, tengo 'undefined'. Pero probé el.attr ("clase"), tengo algo. Entonces, ¿por qué el.attributes devuelve undefined? – Gillespie59

+0

¿Dónde está el el. ¿procedente de? Dentro del ciclo hay dos variables específicamente para el nombre y valor del atributo, solo crea la nueva etiqueta con algo como '$ ('# thetagidORsomething'). Append (' tag') .attr ('id', 'tmp'); 'Luego, dentro del ciclo asigna cada atributo al elemento con el id de' tmp'. Agregué un ejemplo a mi publicación. – Ben

7

Aquí es una solución no elegante, pero trabajando:

// create a new <a> element 
new_element = $("<a/>"); 
// iterate over every attribute of the #some_id span element 
$.each($("#some_id").get(0).attributes, function(i, attrib) { 
     // set each attribute to the specific value 
     $(new_element).attr(attrib.name, attrib.value); 

}); 
// carry over the html content 
new_element.html($("#some_id").html()); 
// finally, swap the elements 
$("#some_id").replaceWith(new_element); 
1

¿Qué está realmente tratando de lograr aquí? Si es solo un estilo, entonces usar CSS sería mejor. Si desea que algo se convierta en un enlace cliqueable (o un enlace para no hacer clic), simplemente puede eliminar el atributo href.

3

Debe utilizar la propiedad outerHtml del HTMLElement que desea cambiar.

De esta manera, se hace muy fácil cambiar un span a un nchor a: sólo tenemos que sustituir ^<span con <a y </span>$ con </a>. Usando una expresión regular para cambiar solo la primera y la última aparición de la etiqueta de apertura y cierre, conservamos los atributos como originalmente.

el código está aquí:

var newElement = $('a-selector').get(0).outerHTML.replace(/^<span/, "<a").replace(/<\/span>$/, "</a>"); 
$('a-selector').replaceWith(newElement); 

este ejemplo se utiliza jQuery. Consulte este fiddle para verlo funcionar.

0

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 
$('span#anId').each(function() { 

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

}); 

La función each utilizo en la primera línea es algo innecesario en este caso, como estamos seleccionando un solo elemento por id . Todavía prefiero usar each aquí, ya que permitiría que este mismo código recorra todos los elementos con una clase específica también.

0

Puede utilizar este código con jQuery:

function replaceElementTag(targetSelector, newTagString) { 
    $(targetSelector).each(function(){ 
     var newElem = $(newTagString, {html: $(this).html()}); 
     $.each(this.attributes, function() { 
      newElem.attr(this.name, this.value); 
     }); 
     $(this).replaceWith(newElem); 
    }); 
} 

Y ejemplo de uso:

replaceElementTag('img', '<amp-img></amp-img>'); 
Cuestiones relacionadas