有没有一种方法可以为querySelectors编写开关语句或其他解决方案

Is there a way of writing switch statements or other solutions for querySelectors?

本文关键字:querySelectors 开关 语句 解决方案 其他 一种 方法 有没有      更新时间:2023-09-26

我目前有

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

但很明显,这在JavaScript中是一种糟糕的做法。

我可以使用交换机案例吗

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>

你不能那样使用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);