Javascript parentNode.getElementById()不工作
我在练习html时遇到了一个问题。当我在JavaScript中使用Javascript parentNode.getElementById()不工作,javascript,html,dom,Javascript,Html,Dom,我在练习html时遇到了一个问题。当我在JavaScript中使用parentNode时,我认为这并不难处理 但是,使用getElementById或其他函数在parentNode下获取某些元素并不是我的想法 var this_question = selectObj.parentNode.parentNode; alert(this_question); //it is working perfectly alert(this_question.getElementById('
parentNode
时,我认为这并不难处理
但是,使用getElementById
或其他函数在parentNode
下获取某些元素并不是我的想法
var this_question = selectObj.parentNode.parentNode;
alert(this_question); //it is working perfectly
alert(this_question.getElementById('question'))
它不起作用了。我不明白
<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>
功能添加问题(selectObj){
var this_question=selectObj.parentNode.parentNode;
警惕(这个问题);//它工作得很好
警报(this_question.getElementById('question')//它不工作。我不明白。。
}
-----
단답형
서술형
다지선
다중선택
规模
부가설명: 답변:
您有两个元素具有相同的id
属性,但id
属性必须是唯一的:
id
属性时,会发生奇怪的事情。例如,如果您将
更改为具有id=“question\u text”
,则情况会更好:
从:
id=name[CS]此属性为元素指定名称。此名称在文档中必须是唯一的 从以下方面:
id
属性指定其元素的唯一标识符(id)。该值在元素的主子树中的所有ID中必须是唯一的,并且必须至少包含一个字符
getElementById()是一种文档方法,在元素中不可用
您可以使用:
this_question.getElementsByTagName('textarea')[0]
getElementsByTagName()在元素中可用。您可以使用:
baseElement.querySelector('#' + id)
它返回:
与指定的选择器组匹配的baseElement的第一个子元素
见:
您想获得哪一个元素的参考?谢谢您的回答。我根据你的答案编辑了id。但它还不起作用。我也用getElementsByName测试了这个。。。我在google Chrome和safari上测试了这段代码。@sandfox:你说“不工作”是什么意思?哪个浏览器?你试过我问题中的链接了吗?哦,我又编辑了我的评论。抱歉:)Chrome和Safari在Chrome、Safari、Firefox和Opera中不起作用。你在HTML和JavaScript中都更新了
id
了吗?jsfiddle.net/munical/67DZr也适用于我。但通过我的服务器,这段代码在chrome上还不起作用:(…我再试一次。谢谢:)。太完美了。但是使用getElementsByName()怎么样?我不明白为什么它不像TagName那样工作。getElementsByName在元素中也不可用