简体   繁体   中英

How do I find matching subtree of HTML nodes in plain JavaScript

I would like to basically do this:

Given our DOM looks like this:

<div class="foo bar">
  <ul class="a b c">
    <li class="even">
      <span id="span1">Hello</span>
    </li>
    <li>
      <span id="span2">World</span>
    </li>
    <li class="even">
      <span id="span3">!!!</span>
    </li>
  </ul>
</div>

How do I say if it matches this pattern?

<ul class="a c">
  <li class="even">

  </li>
</ul>

Or that it matches this pattern:

<ul class="b">
  <li>
    <span>Hello</span>
  </li>
</ul>

Something like this:

matches(el, <ul class="b"><li><span></span></li></ul>)

Some notes:

  • there won't be any wildcards like matching dynamic tag names.
  • these are just partial trees, and the attributes values are sometimes a subset, like the class names in the above example.

Just could not tell you how to match the span with text inside. Other than that, all other elements can be checked with css selectors in javascript, like this:

 if (document.querySelector("ul.ac > li.even")) console.log("Patern 1 found") if (document.querySelector("ul.b > li > span")) console.log("Patern 2 found") if (document.querySelector("ul.ac > li.odd")) console.log("Patern 3 found") 
 <div class="foo bar"> <ul class="abc"> <li class="even"> <span id="span1">Hello</span> </li> <li> <span id="span2">World</span> </li> <li class="even"> <span id="span3">!!!</span> </li> </ul> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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