parentNode.getElementById()不起作用

Jef*_*ang 3 html javascript dom

我在练习HTML时遇到了一个问题.当我parentNode在JavaScript中使用时,我认为它并不难对待.

但是,parentNode使用getElementById或其他功能获得一些元素并不像我的想法那样.

var this_question = selectObj.parentNode.parentNode;
    alert(this_question); //it is working perfectly
    alert(this_question.getElementById('question'))
Run Code Online (Sandbox Code Playgroud)

它不起作用.我无法理解......

<script>
function addQuestion(selectObj) {
    var this_question = selectObj.parentNode.parentNode;
    alert(this_question); //it is working perfectly
    alert(this_question.getElementById('question')) //It's not working. I can't understand..
}
</script>

<ol id="question_list">
    <li>
        <textarea class="question" name="question" id="question"></textarea>
        <select name="question_type" id="question_type" onChange="javascript:selectEvent(this)">
            <option>-----</option>
            <option value="text" >???</option>
            <option value="paragraph" >???</option>
            <option value="multiple_choice">???</option>
            <option value="checkbox">????</option>
            <option value="scale">scale</option>
        </select>   

        <div id='answer_div'><p>????:<input name='top_label' id='top_label' type='paragraph' /></p> <p>??:<input name='answer_text' id='answer_text' type='text' /></p></div>

        <p>
            <input type="button" value="Add Question" onclick="javascript:addQuestion(this)"/>
            <input type="button" value="Done" onclick="javascript:finish()"/>
         </p>
    </li>
</ol>
Run Code Online (Sandbox Code Playgroud)

Dr.*_*lle 7

getElementById()是一种文档方法,在元素中不可用.

你可以使用:

this_question.getElementsByTagName('textarea')[0]
Run Code Online (Sandbox Code Playgroud)

getElementsByTagName()在元素中可用.


mu *_*ort 2

您有两个具有相同id属性的元素,但id属性必须是唯一的:

  1. <ol id="question">
  2. <textarea class="question" name="question" id="question"></textarea>

当你复制id属性时,就会发生奇怪的事情。例如,如果将 更改<textarea>为 has ,事情就会开始更好地工作:id="question_text"

http://jsfiddle.net/ambigously/67DZr/

来自HTML4 规范

id = name [CS]
该属性为元素分配一个名称。该名称在文档中必须是唯一的。

以及HTML5 规范

id属性指定其元素的唯一标识符 (ID)。该值在元素的主子树中的所有 ID 中必须是唯一的,并且必须至少包含一个字符。