Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:完成的很好, 继续加油
DOM元素的获取方法主要由获取某个元素,获取子元素,第一个子元素,最后一个子元素和某一个子元素等。常用的获取方法见下面的例子。
<ul class="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 -->
<form action="#" method="post" name="myForm">
<fieldset>
<caption>表单框</caption>
<div>
<label for="age">输入年龄:</label>
<input type="number" name="age" id="age" value="20">
</div>
<br>
<div>
<label for="surname">输入姓名:</label>
<input type="text" name="surname" id="surname" >
</div>
<br>
<div>
<label for="date">选择日期:</label>
<input type="date" name="date" id="dat3">
</div>
<br>
<div>
<label>请选择城市</label>
<select name="city">
<option value="beijing">北京</option>
<option value="shijiazhuang">石家庄</option>
<option value="jinan">济南</option>
<option value="hefei">合肥</option>
<option value="shenyang">沈阳</option>
</select>
</div>
<br>
<button type="button" onclick="acquire()">提交</button>
<button type="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 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中是否还有某个子元素contains()
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.textContent);
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.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>