Come modificare gli attributi HTML in una stringa grezza con Jquery o Javascript?
Voglio prendere un gruppo di tag di ancoraggio e assicurarmi che tutti si aprano in una nuova scheda.
So che dovrei fare qualcosa del genere $ ('a').attr('target', '_blank'); ma il problema è che l'HTML che sto cercando di modificare si trova in una variabile stringa.
Vedi esempio:
Ho un mucchio di HTML grezzo in una stringa come questa:
var rawHTML = 'Hello there, <a href="http://www.google.com">this</a> is a link.'
Come posso convertire quello per essere qualcosa di simile a questo:
processedHTML = 'Hello there, <a href="http://www.google.com" target="_blank">this</a> is a link.'
Risposta n. 1
Usando jQuery puoi aggiungere la stringa a un elemento al di fuori del DOM
Puoi quindi usare i metodi jQuery su questo nuovo elemento per modificare l'html e poi restituire la stringa modificata:
var rawHTML = 'Hello there, <a href="http://www.google.com">this</a> is a link.';
// create element and set string as it's content
var $div = $('<div>').html(rawHTML);
// modify attributes
$div.find('a').attr('target', '_blank');
// return modified content to string
var processedHTML = $div.html();
Risposta n. 2
In JavaScript puro, possiamo fare questo utilizzando i metodi document.createElement, Element.getElementsByTagName e Element.setAttribute, così come la proprietà getter e setter Element.innerHTML.
Nota che Element.getElementsByTagName restituisce un HTMLCollection live, ed è per questo che possiamo istanziare l'oggetto links prima di inserire la stringa html. Per iterare sulla collezione, invochiamo un metodo di array usando la collezione come contesto this.
Questo riduce parte del sovraccarico di jQuery.
function blankify (html) {
var root = document.createElement('span'),
links = root.getElementsByTagName('a');
root.innerHTML = html;
Array.prototype.forEach.call(links, function (e) {
e.setAttribute('target', '_blank');
});
return root.innerHTML;
}
console.log(blankify('Hello there, <a href="http://www.google.com">this</a> is a link.'));E giusto perché, ecco un metodo jQuery abbastanza flessibile. Funziona sul DOM ed è concatenabile.
jQuery.prototype.blankify = function () {
return this.find('a').attr('target', '_blank'), this;
};
console.log($('<span/>', {
html: 'Hello there, <a href="http://www.google.com">this</a> is a link.'
}).blankify().html());<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>