I want to put all attributes in a Html element into an array: like i have a jQuery Object, whichs html looks like this:
Does this help?
This property returns all the attributes of an element into an array for you. Here is an example.
window.addEventListener('load', function() {
var result = document.getElementById('result');
var spanAttributes = document.getElementsByTagName('span')[0].attributes;
for (var i = 0; i != spanAttributes.length; i++) {
result.innerHTML += spanAttributes[i].value + ',';
}
});
To get the attributes of many elements and organize them, I suggest making an array of all the elements that you want to loop through and then create a sub array for all the attributes of each element looped through.
This is an example of a script that will loop through the collected elements and print out two attributes. This script assumes that there will always be two attributes but you can easily fix this with further mapping.
window.addEventListener('load',function(){
/*
collect all the elements you want the attributes
for into the variable "elementsToTrack"
*/
var elementsToTrack = $('body span, body div');
//variable to store all attributes for each element
var attributes = [];
//gather all attributes of selected elements
for(var i = 0; i != elementsToTrack.length; i++){
var currentAttr = elementsToTrack[i].attributes;
attributes.push(currentAttr);
}
//print out all the attrbute names and values
var result = document.getElementById('result');
for(var i = 0; i != attributes.length; i++){
result.innerHTML += attributes[i][0].name + ', ' + attributes[i][0].value + ' | ' + attributes[i][1].name + ', ' + attributes[i][1].value +'
';
}
});