从元素中的子节点获取值

时间:2014-06-23 06:38:50

标签: javascript extract

我想做的事可以分三步完成:
1.找到特定元素
2.在该元素中查找特定的子节点
3.从这些特定子节点中提取值 我知道,这很简单,但我是JavaScript的新手。让我们考虑以下代码,并提供评论以帮助我们。

<!--We're going to look at the content of this "p" tag-->
<p id="demo">
<!--Here we have a textbox and a drop down list-->
<input type="text" value="A Value"/>
<select>
<option value="zero">0</option>
<option value="1">1</option>
</select>
</p>
<!--This is the button that finds the "p" element with an id of "demo", then looks at  its child nodes.-->
<input type="button" onclick="extractV()" value="Get Values"/>
<script>
function extractV() {
document.getElementById("demo").//This is the bit that I don't know.
}
</script>

你去吧。我无法找到正确的标签来查找该标签中的特定节点(或任何相关的节点),然后提取它们的值,但我知道这是一种方法。如果你知道它会很棒。我非常感谢任何帮助我努力的帮助。即使是建设性的批评我也不介意。谢谢!

P.S:不要以为我来Stack Overflow问愚蠢的问题。我已经咨询过书籍和其他人。这是我的最后一招。如果您对该问题有疑问,请询问。

1 个答案:

答案 0 :(得分:1)

我不确定,但我认为这就是你想要的http://jsfiddle.net/Kzwt9/

<!--We're going to look at the content of this "p" tag-->
<p id="demo">
<!--Here we have a textbox and a drop down list-->
<input type="text" value="A Value"/>
<select>
<option value="zero">0</option>
<option value="1">1</option>
</select>
</p>
<!--This is the button that finds the "p" element with an id of "demo", then looks at  its child nodes.-->
<input id="extractv" type="button" value="Get Values"/>
<script>
function extractV() {
  els = document.getElementById("demo").childNodes;
  for (var i = 0; i < els.length; ++i) {
    console.log( els[i].value );
  }
}
document.getElementById("extractv").addEventListener('click',extractV, false);
</script>
相关问题