簡體   English   中英

如何選擇最高匹配的后代

[英]How to select the highest matching descendants

我正在處理 HTML 內容,其中作者可能會在特定元素上設置一個類,內容可能會被動態插入,並且開發人員可能擁有也將相同類應用於選擇元素的代碼。 我需要從除最高后代之外的所有人中修剪該類。 我有一個遞歸函數,它已經通過使用 querySelectorAll(selector) 來執行此操作,並且對於每個匹配項,它會爬上樹,如果沿途的任何父級具有相同的類,則刪除后代的類。 它這樣做直到它到達 body 元素。 因此,對於大量的內容,它只是幾個相當密集的轉換之一。

我希望我忽略了一種更快的方法,可能是本機函數或精益選擇器表達式。

例如,在下面,我只想保留兩個分支。 如果我能找到一種只選擇這兩個的通用方法,則可以比從每個匹配項中遞歸檢查更快地修剪嵌套分支的類:

<div class="content">
    <div class="branch"> <!-- Keep this -->
        <div class="branch">
            <div class="branch"></div>
        </div>
    </div>
    <div>
        <div>
            <div class="branch"> <!-- Keep this -->
                <div>
                    <div class="branch"></div>
                </div>
            </div>
        </div>
    </div>
</div>

更新:在研究解決方案時,我意識到我不必使用遞歸,我可以隨時修剪Array.from([selector results]) 所以這會加快一些速度,但我仍然認為我忽略了一個明顯的選擇器表達式或錯過了本機函數。 我還發現了 node.contains(),但我還沒有看到利用它的好方法。

我相信以下是解決您的問題的最簡單方法,並且可能會表現得很好:

 console.log(`------ BEFORE ------ ${document.getElementById('container').outerHTML}`) // the next three lines are all you need document.querySelectorAll('.branch .branch').forEach( el => el.classList.remove('branch') ) console.log(`------ AFTER ------ ${document.getElementById('container').outerHTML}`)
 .as-console-wrapper { max-height: 100% !important; top: 0; }
 <div class="content" id="container"> <div class="branch"> <!-- Keep this --> <div class="branch"> <div> <div class="branch"></div> </div> </div> </div> <div> <div> <div class="branch"> <!-- Keep this --> <div> <div class="branch"></div> </div> </div> </div> </div> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM