html - Cannot retrieve an li or ul using getElementById in JavaScript - Stack Overflow

I can get an HTML object using JavaScript using the function document.getElementById('id'). I

I can get an HTML object using JavaScript using the function document.getElementById('id'). If I get a form, then I can further specify an element in the form by doing something like the following:

document.getElementById('form_id').form_element.value="hello world";

This works if the elements in the form are inputs and text areas. (I haven't tried them all...) However, this doesn't work for unordered lists or list elements. I can't specify an li element once I get an element using a form. Does anyone know why that is? Also, the unordered list is used across different forms, so I can't give it a unique id. (Unless I copy paste code everywhere...)

I can get an HTML object using JavaScript using the function document.getElementById('id'). If I get a form, then I can further specify an element in the form by doing something like the following:

document.getElementById('form_id').form_element.value="hello world";

This works if the elements in the form are inputs and text areas. (I haven't tried them all...) However, this doesn't work for unordered lists or list elements. I can't specify an li element once I get an element using a form. Does anyone know why that is? Also, the unordered list is used across different forms, so I can't give it a unique id. (Unless I copy paste code everywhere...)

Share Improve this question asked Jul 3, 2013 at 1:36 SalSal 3,2697 gold badges33 silver badges41 bronze badges 5
  • 1 Check here developer.mozilla/en-US/docs/Web/API/… – elclanrs Commented Jul 3, 2013 at 1:40
  • @elclanrs, thanks, that's on the right track. Do you know if I can specify a selector by id or name? – Sal Commented Jul 3, 2013 at 1:47
  • You can specify any valid CSS selector. Just mind old browsers... – elclanrs Commented Jul 3, 2013 at 1:51
  • Just curious, why aren't you using jQuery? – jedmao Commented Jul 3, 2013 at 5:32
  • @sfjedi lack of experience, that's all. I'm a programmer, but I wanted to help a friend with a site. – Sal Commented Jul 3, 2013 at 16:42
Add a ment  | 

1 Answer 1

Reset to default 2

You can run .getElementsByTagName('ul') on any DOM element. For example, using the following HTML:

<form id="form_id">
    <input name="form_element"/>
    <ul>
        <li>foo</li>
        <li>bar</li>
    </ul>
</form>

Do this:

var form = document.getElementById('form_id');
form.form_element.value = 'hello world';

var ul = form.getElementsByTagName('ul');
ul = ul && ul[0];
console.log(ul);

var lis = form.getElementsByTagName('li');
for (var i = 0; i < lis.length; i++) {
    console.log(lis[i].innerText);
}

jsFiddle here: http://jsfiddle/YSpVg/1/

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745321931a4622480.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信