mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
net.html: add Tag.get_tags() (#13102)
This commit is contained in:
parent
92fcb82ca3
commit
e2a0046849
@ -66,3 +66,39 @@ pub fn (tag &Tag) str() string {
|
||||
}
|
||||
return html_str.str()
|
||||
}
|
||||
|
||||
// get_tags retrieves all the child tags recursively in the tag that has the given tag name.
|
||||
pub fn (tag &Tag) get_tags(name string) []&Tag {
|
||||
mut res := []&Tag{}
|
||||
for child in tag.children {
|
||||
if child.name == name {
|
||||
res << child
|
||||
}
|
||||
res << child.get_tags(name)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// get_tags_by_attribute retrieves all the child tags recursively in the tag that has the given attribute name.
|
||||
pub fn (tag &Tag) get_tags_by_attribute(name string) []&Tag {
|
||||
mut res := []&Tag{}
|
||||
for child in tag.children {
|
||||
if child.attributes[name] != '' {
|
||||
res << child
|
||||
}
|
||||
res << child.get_tags_by_attribute(name)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
// get_tags_by_attribute_value retrieves all the child tags recursively in the tag that has the given attribute name and value.
|
||||
pub fn (tag &Tag) get_tags_by_attribute_value(name string, value string) []&Tag {
|
||||
mut res := []&Tag{}
|
||||
for child in tag.children {
|
||||
if child.attributes[name] == value {
|
||||
res << child
|
||||
}
|
||||
res << child.get_tags_by_attribute_value(name, value)
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
37
vlib/net/html/tag_test.v
Normal file
37
vlib/net/html/tag_test.v
Normal file
@ -0,0 +1,37 @@
|
||||
module html
|
||||
|
||||
const (
|
||||
html = '<!doctype html>
|
||||
<html>
|
||||
<head></head>
|
||||
<body>
|
||||
<div id="1st">
|
||||
<div class="bar"></div>
|
||||
</div>
|
||||
<div id="2nd">
|
||||
<div class="foo">
|
||||
<a href="https://vlang.io/">V</a>
|
||||
</div>
|
||||
<div class="bar"></div>
|
||||
<a href="https://modules.vlang.io/">vlib</a>
|
||||
<div class="bar">
|
||||
<div class="bar">
|
||||
<p>
|
||||
<div>modules</div>
|
||||
</p>
|
||||
<a href="https://vpm.vlang.io/">vpm</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="3rd"></div>
|
||||
</body>
|
||||
</html>'
|
||||
)
|
||||
|
||||
fn test_search_by_tag_type() {
|
||||
mut dom := parse(html.html)
|
||||
tag := dom.get_tag_by_attribute_value('id', '2nd')[0]
|
||||
assert tag.get_tags('div').len == 5
|
||||
assert tag.get_tags_by_attribute('href')[2].content == 'vpm'
|
||||
assert tag.get_tags_by_attribute_value('class', 'bar').len == 3
|
||||
}
|
Loading…
Reference in New Issue
Block a user