Estaba tratando de hacer una función que le brinde las propiedades CSS seleccionadas de un elemento que desea. Pero es bastante lento si se usa en la consola, ya que necesita obtener y hacer coincidir todas las propiedades de CSS.
function styleOf(elementUseSelectors, propertiesToCheck, tellInConsole) { var element = elementUseSelectors; var Arguments = propertiesToCheck; var calculatedProperties = []; var matchedProperties = []; if (tellInConsole !== undefined && tellInConsole == true) { console.warn("Running styleOf() Please Don't Do Other Calculations This Function Disables Console.") } for (var i = 0; i < Object.keys(getComputedStyle(element)).length; i++) { var value = getComputedStyle(element).getPropertyValue(Object.entries(getComputedStyle(element))[i][0].replace(/([AZ])/g, ' $1').trim().replaceAll(" ", "-").toLowerCase()); if (value !== "") { calculatedProperties.push(Object.entries(getComputedStyle(element))[i][0].replace(/([AZ])/g, ' $1').trim().replaceAll(" ", "-").toLowerCase() + ": " + value); } } for (var i = 0; i < calculatedProperties.length; i++) { for (var a = 0; a < Arguments.length; a++) { if (calculatedProperties[i].includes(Arguments[a])) { window.splitted = calculatedProperties[i].split(""); window.joinThis = []; for (var k = 0; k < splitted.indexOf(":"); k++) { joinThis.push(splitted[k]); }; if (joinThis.join("") == Arguments[a]) { matchedProperties.push(calculatedProperties[i]); } } } } if (tellInConsole !== undefined && tellInConsole == true) { console.warn("StyleOf() Calculations Completed You Can Now Use Console.") } return matchedProperties }El objeto TreeWalker está diseñado para analizar rápidamente los nodos DOM en un documento. Si amplía el ejemplo dado anteriormente en MDN Web Docs, puede generar las propiedades CSS calculadas para un nodo determinado.
La primera propiedad del método es el nodo que desea recorrer; en este caso, es document.body :
var treeWalker = document.createTreeWalker( document.body, NodeFilter.SHOW_ELEMENT, { acceptNode: function(node) { return NodeFilter.FILTER_ACCEPT; } }, false ); var nodeList = []; var currentNode = treeWalker.currentNode; while(currentNode) { nodeList.push(currentNode); const style = getComputedStyle(currentNode) console.log(style) currentNode = treeWalker.nextNode(); console.log("moving to next node..."); }Bien, @kaiido respondió la pregunta.
function styleOf(element, properties) { const computed = getComputedStyle(element); return properties.map( key => key + ": " + computed[ key ] )}; var style = styleOf(document.getElementsByTagName("body")[0], ["height", "width", "background-color", "font-size", "color", "font-family"]); console.log(style);