2012-03-03 19 views
7

Voglio ottenere tutte le classi dell'elemento HTML sulla mia pagina, dividerlo e archiviarlo in serie. Dopodiché voglio scriverlo nel mio tavolo nel div con l'id "table" che ho già.Crea tabella HTML da javascript array

Finora ho questo codice:

var string = $('html').attr('class'); 
var array = string.split(' '); 
var arrayLength = parseInt(array.length); 

for (i=0; i<=arrayLength; i++) { 
    // code 
} 

<div id="test><!-- table goes here --></div> 

mi potete aiutare con il resto?

btw, l'elemento HTML ha le classi da un modernizr.js.

PS: Il codice è una combinazione di JS puro e jQuery. Perché non so come ottenere tutte le classi dell'elemento HTML in puro JS. Qualche idea?

risposta

9

Se stai cercando di rimuovere del tutto jQuery utilizzare questo:

// Get array of classes without jQuery 
var array = document.getElementsByTagName('html')[0].className.split(/\s+/); 

var arrayLength = array.length; 
var theTable = document.createElement('table'); 

// Note, don't forget the var keyword! 
for (var i = 0, tr, td; i < arrayLength; i++) { 
    tr = document.createElement('tr'); 
    td = document.createElement('td'); 
    td.appendChild(document.createTextNode(array[i])); 
    tr.appendChild(td); 
    theTable.appendChild(tr); 
} 

document.getElementById('table').appendChild(theTable); 

JSFiddle esempio che mostra la tabella.

+0

+1 per l'utilizzo di funzioni di manipolazione DOM native native anziché innerHTML (sebbene il termine "efficiente" sia molto discusso ...) – David

2

se si dispone di una tabella già in html

<div id="test><table > 
    </table> 
</div> 

si può semplicemente append nuove righe ad esso,

var string = $('html').attr('class'); 
var array = string.split(' '); 
var arrayLength = parseInt(array.length); 

for (i=0; i<=arrayLength; i++) { 
    $("#test table") .append('<tr><td>'+array[i]+'</td></tr>') 
} 
2

Non è chiaro se si desidera che i nomi di classe per riga o per colonna. Questi esempi sono un nome di classe per riga. Prova questo:

var elm = $('#test'), 
    table = $('<table>').appendTo(elm); 

$(document.documentElement.className.split(' ').each(function() { 
    table.append('<tr><td>'+this+'</td></tr>'); 
}); 

Ho usato il codice nativo per ottenere i classnames dell'elemento HTML: document.documentElement.className, ma si potrebbe anche usare $('html').attr('class').

Un esempio nativo JS utilizzando innerHTML:

var d = window.document, 
    elm = d.getElementById('test'), 
    html = '<table>', 
    classes = d.documentElement.classNames.split(' '), 
    i = 0; 

for(; classes[i]; i++) { 
    html += '<tr><td>' + classes[i] + '</td></tr>'; 
} 

elm.innerHTML = html + '</table>;