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
1 Answer
Reset to default 2You 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条)