简体   繁体   English

嵌套类的Javascript CSS选择器

[英]Javascript css selector for nested classes

I am creating a CSS selector for homework. 我正在为作业创建CSS选择器。 I have managed to extract and get single selectors - eg #_id , but I cannot work out how to get a result for nested ones such as : div#_id._class [NOTE: I cannot use any libraries to do this or querySelectorAll ] 我已经设法提取并获得了单个选择器-例如, #_id _ #_id ,但是我#_id如何获得嵌套选择器的结果,例如: div#_id._class [注意:我不能使用任何库来做到这一点或querySelectorAll ]

The pseudo-code below is an example of what I currently have: 下面的伪代码是我目前拥有的示例:

if (regex match for class) {
    for (a in match for class) {
        if (a.indexOf('.') > -1) {
            var split_ = a.split(".");
            var dot = split_[0];
            var class_ = split_[1];
            array_of_elements = document.getElementsByClassName(class_);
        }
    }

The problem is when the selector is nested I can't extract the whole thing using a similar method. 问题是当选择器嵌套时,我无法使用类似的方法提取全部内容。 Eg look for an id, look for a class. 例如,寻找一个ID,寻找一个类。 Can anyone point me in the right direction? 谁能指出我正确的方向?

else if (is id) {
    split by ("#");
    for (each result) {
        if (has class ('.')) {
            array_elements = document.getElementById(result_ID)
                             .getElementsByClassName(result_CLASS_NAME));
        } else {
            array_elements = (document.getElementsByTagName(result));
        }
    }

What you mentioned is actually called a sequence of simple selectors . 您所说的实际上称为简单选择器序列

div#_id._class

It consitst of three simple selectors div , #_id , ._class 它由三个简单的选择器 div#_id._class

What you need to do is get elements by tag name, and then check for matches on all of the remaining simple selectors. 您需要做的是通过标记名称获取元素,然后检查所有其余简单选择器上的匹配项。 I'll give you an idea here: 我在这里给你一个主意:

function qSelector(sequence) {
    var tagName = getTag(sequence) || '*'; // 'div'
    var ids = getIDs(sequence); // ['_id']
    var classes = getClasses(sequence); // ['_class']
    var els = document.getElementsByTagName(tagName);
    return [].filter.call(els, function (el) {
        for (id in ids) { if (el.id != id) return false; }
        for (cls in classes) { if (el.className not contains cls) return false; }
        return true;
    });
}

This is more versatile than your approach and can be easily generalized to work with selectors containing spaces. 这比您的方法更具通用性,并且可以轻松地推广到包含空格的选择器。

I'll leave the implementation of the get… helpers to you. 我将把get… helpers的实现留给您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM