Finding arbitrary HTML nodes that have specific attributes with specific value #976
-
I want to find arbitrary html nodes that have <div>
<article class="foo">
Lorem ipsum....
</article>
<p class="bar">
Lorem ipsum....
</p>
<div class="foo">
Lorem ipsum....
</div>
</div> To do so, I ran the following command but I get an empty result. ast-grep --pattern '<$TAG class="foo">$$$</$TAG>' index.html |
Beta Was this translation helpful? Give feedback.
Answered by
HerringtonDarkholme
Mar 9, 2024
Replies: 1 comment 6 replies
-
tree-sitter does not allow $ in tagname. you can use yaml instead.https://ast-grep.github.io/guide/rule-config.html |
Beta Was this translation helpful? Give feedback.
6 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I mean you can avoid using $TAG as a tag name in pattern and use YAML to directly find the attribute. Then find the element having that attribute. All these steps can be composed by YAML rules.
This is done by several step:
class="foo"
https://ast-grep.github.io/guide/rule-config/atomic-rule.html#patternthis is the critical step that we avoid the
$TAG
kind: element
to find the HTML element andhas
to find the element containing the attribute. (But note it does not work sincehas
by default only searches direct children)stopBy
can instruct ast-grep to find descendants. In this case, we want to only find elements that have attributes …