通过JavaScript读取表单中<input />以外的标签

时间:2017-08-18 20:23:58

标签: javascript

我有以下HTML:

<form name="quiz" onsubmit="return Result()">
    <h3>1. What are the right order of the seasons?</h3>
    <input type="radio" name="radio1" value="a">a.  Spring, Summer, Autumn, Winter<br />
    <input type="radio" name="radio1" value="b">b. Spring, Winter, Summer, Autumn<br />
    <input type="radio" name="radio1" value="c">c.  Spring, Summer, Winter, Autumn<br />
    <input type="radio" name="radio1" value="d">d.  Summer, Autumn, Spring, Winter<br />

    <h3>2. Normally, how many days are there in a year?</h3>
    <input type="radio" name="radio2" value="a">a.  364<br />
    <input type="radio" name="radio2" value="b">b.  365<br />
    <input type="radio" name="radio2" value="c">c.  366<br />
    <input type="radio" name="radio2" value="d">d.  367<br />
    <input type="submit" value="Submit Answers">
</form>

我想计算表单中有多少标签,但是当我使用document.quiz.length方法时,它只统计<input>标签(它为上面的代码段计算了9个元素)所以我无法前往<h3>。你能告诉我如何计算<h3>吗?谢谢!

2 个答案:

答案 0 :(得分:0)

您可以使用方法document.getElementById("yourForm").childElementCount。此方法将计算html节点的所有子节点。说明:此方法计算表单或div中的所有标记...您可以查阅w3schools'文档。

此功能完成工作:

function count() {
var c = document.getElementById("yourForm").childElementCount;
console.log (c);
}

答案 1 :(得分:0)

你想要的是计算表格中有多少个标签?使用document.querySelectorAll和直接子CSS选择器很容易:

let tagAmoungInDatForm = document.querySelectorAll('form[name="quiz"] > *').length;


如果您特别想要计算h3那么:

let tagAmoungInDatForm = document.querySelectorAll('form[name="quiz"] > h3').length;

您还可以使用children.length

let form = /*select form*/;
let tagAmountInDatForm = form.children.length;

childElementCount

let form = /*select form*/;
let tagAmountInDatForm = form.childElementCount;