@maxefect

Как получить селектор CSS, зная только css-свойство?

Допустим, у нас есть
#max {width:300px}
div {height:500px}
img.New, span {border:1px solid red}

Как можно получить при помощи чистого javascript именно название селектора?

Пример:

e('width'){
return nameSelector[то есть выдаст #max], value[то есть 300px]
}

e('height'){
return nameSelector[то есть выдаст div], value[то есть 500px]
}

e('border'){
return nameSelector[то есть выдаст img.New, span], value[то есть 1px solid red]
}
  • Вопрос задан
  • 2608 просмотров
Пригласить эксперта
Ответы на вопрос 1
Если вас правильно понял, вот ~ код:
var slice = Array.prototype.slice,
    filter = Array.prototype.filter
    ;

function findSelector(cssProperty){
    var rules = [];
    
    filter
        .call(document.styleSheets, hasRules)
        .forEach(function(styleSheet){
            
            rules = rules.concat(slice
                .call(styleSheet.rules)
                .filter(hasCssNameDelegate(cssProperty))
            );
        })
    
    return rules.map(function(rule){
        return {
            selector: rule.selectorText,
            value: rule.style[cssProperty]
        };
    });
    
    function hasRules(styleSheets){
        return styleSheets.rules != null
    }
    
    function hasCssNameDelegate(name) {
        return function(cssRule){
            return cssRule.style && slice.call(cssRule.style).indexOf(name) !== -1
        };
    }
}

function findSelectorForElement(element, cssProperty){
    var matchesSelector = HTMLElement.prototype.webkitMatchesSelector
        || HTMLElement.prototype.mozMatchesSelector
        || HTMLElement.prototype.msMatchesSelector
        || HTMLElement.prototype.oMatchesSelector
        ;
        
    return findSelector(cssProperty)
        .filter(function(data){
            return matchesSelector.call(element, data.selector);
        
        }).slice(-1)[0];
}

var tosterSidebar = document.querySelector('.sidebar')
findSelectorForElement(tosterSidebar, 'width');
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы