我正在寻找一个工具,它可以让我检查某个HTML片段是否在其正确的上下文中有效。
我可以输入如下内容
<dd>
my definition
<div>
div inside <dd> is allowed
</div>
</dd>
而不是整个文档。普通的验证器会抱怨缺少dl-tag,但大多数时候我只是想知道某个元素在另一个元素里面是否有效。
我将尝试更详细地解释一下。考虑下面的片段。
<form>
<label>Name: <input /></label>
</form>
将是有效的,但要检查它,我有两个选择:
基本上,我想检查一个元素是否只包含它允许包含的元素。
实际上,您可以使用W3C验证器来检查一个代码段。
选择 "Validate by Direct Input "标签,然后选择 "更多选项"。在那里有一个单选按钮 "Validate HTML fragment"。http:/validator.w3.org#validate_by_input+with_options。
它将用有效的 html 来包装您的页面,所以您看到的错误只是由于您的片段造成的。
W3C目前(2020年5月)确实有一个片段验证器,但它似乎有bitrot(至少没有HTML5)。这里有几个简单的脚本,可以给你的片段附加一个页眉和页脚,并通过本地副本运行结果。Nu checker. 该片段可以是任何有效的顶级的 <body>
标签--如果你需要其他东西,请修改页眉和页脚。
validate1.sh
需要一个单一的文件名参数并检查它,而 validate2.sh
循环浏览一个目录中的所有HTML文件。它有一个简单的排除列表机制,你需要修改它。你需要修改这两点,使其指向你的拷贝的 vnu.jar
.
validate1.sh
:
#!/bin/bash
#
# validate1.sh
#
# Run the nu validator on the HTML fragment in the supplied filename.
# This script adds a header and trailer around the fragment, and supplies
# the result to 'vnu.jar'. You'll need to modify it to correctly locate
# vnu.jar.
if test "$#" -ne 1; then
echo "Usage: '$0 fname', where 'fname' is the HTML file to be linted"
exit 1
fi
var="<!doctype html>
<html lang=\"en\">
<head>
<title>foo</title>
</head>
<body>
$(< "$1")
</body>
</html>"
echo "Checking '$1'... subtract 6 from any reported line numbers"
echo "$var" | java -jar vnu.jar -
validate2.sh
:
#!/bin/bash
#
# validate2.sh
#
# Run the nu validator on the HTML fragments in the supplied directory. This
# script adds a header and footer around each fragment in the directory, and
# supplies the result to 'vnu.jar'. You'll need to modify it to correctly
# locate vnu.jar.
if test "$#" -ne 1; then
echo "Usage: '$0 fname', where 'fname' is the HTML directory to be linted"
exit 1
fi
for filename in $1/*.html; do
case $filename in
# simple exclusion list example:
"$1/root.html" | "$1/sitedown.html")
echo "Skipping '$filename'"
continue
;;
*)
;;
esac
var="<!doctype html>
<html lang=\"en\">
<head>
<title>foo</title>
</head>
<body>
$(< "$filename")
</body>
</html>"
echo "Checking '$filename'... subtract 6 from any reported line numbers"
echo "$var" | java -jar vnu.jar -
done