有没有办法为querySelectors编写switch语句或其他解决方案?

时间:2015-11-09 16:34:49

标签: javascript

我目前有

if (element.querySelector('h1:first-child') || element.querySelector('container')) {
     removeBorderClass();
}

if (element.querySelector('h3:first-child')) {
     removeBorderClass();
}

但显然这在JavaScript中是一种不好的做法。

我可以使用Switch case

switch(element.querySelector())
     case 'h3:first-child' || 'container'
     break;
//this is an example

还是有更好的解决方案吗?

<section>
    <h1>h1 is first child of section</h1>
    //it should remove the border
</section>

<section>
    <h2>h1 is first child of section</h2>
    //it should not remove the border
</section>

1 个答案:

答案 0 :(得分:5)

你不能像这样使用switch / case,如果那个模式重复很多,你可以将它重构为它自己的函数:

function ifHasMatchingChildren(parent, selectors, callback) {
    // or, if you want to get fancy
 // if (selectors.some(parent.querySelector.bind(parent)) {
    if (selectors.some(selector => parent.querySelector(selector))) {
        return callback();
    }
}

ifHasMatchingChildren(element, ['h1:first-child', 'container'], () => 
    removeBorderClass());
// can even be shortened with the following
ifHasMatchingChildren(element, ['h3:first-child'], removeBorderClass);