DOM元素的获取及遍历方法实例
DOM元素的获取方法
DOM元素的获取方法主要由获取某个元素,获取子元素,第一个子元素,最后一个子元素和某一个子元素等。常用的获取方法见下面的例子。
<ulclass=“list”><li>item1</li><li>item2</li><li>item3</li><li>item4</li><li>item5</li><li>item6</li><li>item7</li><li>item8</li></ul><!– 获取表单中中元素的值document.forms.inputname.value –><formaction=“#”method=“post”na源码搭建wcqh.cnme=“myForm”><fieldset><caption>表单框</caption><div><labelfor=“age”>输入年龄:</label><inputtype=“number”name=“age”id=“age”value=“20”></div><br><div><labelfor=“surname”>输入姓名:</label><inputtype=“text”name=“surname”id=“surname”></div><br><div><labelfor=“date”>选择日期:</label><inputtype=“date”name=“date”id=“dat3”源码搭建wcqh.cn></div><br><div><label>请选择城市</label><selectname=“city”><optionvalue=“beijing”>北京</option><optionvalue=“shijiazhuang”>石家庄</option><optionvalue=“jinan”>济南</option><optionvalue=“hefei”>合肥</option><optionvalue=“shenyang”>沈阳</option></select></div><br><buttontype=“button”onclick=“acquire()“>提交</button><b源码搭建wcqh.cnuttontype=“reset”>重置</button></fieldset></form> <script> let ul = document.querySelector(“.list”); console.log(ul);// 获取ul第一个子元素 let firstchild = ul.firstElementChild; console.log(firstchild.textContent);// 获取ul第一个子元素的下一个元素 let nextFirst = firstchild.nextElementSibling; console.log(“The next element of the first源码搭建wcqh.cn element is: “+nextFirst.textContent);// 获取ul的最后一个子元素 let lastChild = ul.lastElementChild; console.log(lastChild.textContent);// 获取最有一个子元素前边的元素 let previousElement = lastChild.previousElementSibling; console.log(“The previous element of the last element is: “+previousElement.textContent);// ul中是否还有某个子元素cont源码搭建wcqh.cnains() console.log(ul.contains(firstchild));// 获取ul所有子元素的内容 let child = ul.children; console.log(child);[…child].forEach(element => console.log(element.textContent));//获取ul的第X个子元素 let fifthElement = document.querySelector(.list>li:nth-of-type(5)); console.log(“The fifth element is : “+ fifthElement.textConten源码搭建wcqh.cnt); let fifthElement_2 = ul.children[1]; console.log(“The second way to acquire thefifth element : “+ fifthElement_2.textContent);// 获取表单元素// 1.获取表单 let forms = document.forms.myForm; console.log(forms);// 2.获取年龄框function acquire(){// 获取表单中元素的值 forms.input-name.value console.log(`The age you inut is :${forms.age源码搭建wcqh.cn.value}`); console.log(`The surname you input is : ${forms.surname.value}`); console.log(`The date you choose is:${forms.date.value}`); console.log(`The city you choose is:${forms.city.value}`);}</script>© 版权声明
1.如需技术支持联系QQ:1339833655
2. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
3. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
4. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
5. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
6. 如有链接无法下载、失效或广告,请联系管理员处理!
7. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
8. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员!
THE END
暂无评论内容