Ho il seguente codice
<b class="xyzxterms" style="cursor: default; ">bryant keil bio</b>
Come sostituirei il btag con un h1tag ma conservo tutti gli altri attributi e informazioni?
Ho il seguente codice
<b class="xyzxterms" style="cursor: default; ">bryant keil bio</b>
Come sostituirei il btag con un h1tag ma conservo tutti gli altri attributi e informazioni?
Risposte:
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/
childrennon ha funzionato ma contentsha funzionato.
.eachblocco come mostra anche una risposta sotto.
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);
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] .
while(child = child.nextSibling)non è riuscito. Grazie!
@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);
};
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.)
eachciclo).
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);
});
@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');
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);
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());
});
});
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...
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.
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;
};