jquery查找后代元素 children() contents() find()
所謂的后代元素,就是某個元素的“子元素”、“孫元素”……。孫元素,在前端雖然沒這個說法,但是卻比較形象,所以這一節使用這一個說法。
一、children()方法
在jQuery中,我們可以使用children()方法來查找當前元素的“所有子元素”或“部分子元素”。注意,children()方法只能查找子元素,不能查找其他后代元素。
<script type=
"text/javascript"
>
$(
function
() {
$(
".wrapper"
).hover(
function
() {
$(
this
).children(
".test"
).text(
"www.nanaopearl.com
"
);
},
function
() {
$(
this
).children(
".test"
).text(
"www.nanaopearl.com
"
);
})
})
</script>
二、contents()方法
與children()方法相似,contents()方法也是用來查找子內容的,但它不僅獲取子元素,還可以獲取文本節點、注釋節點等。因此讀者可以把它視為DOM中childNodes屬性的jQuery實現。contents()方法很少用,作為初學者我們可以直接忽略這個方法。
三、find()方法
find()方法和children()方法相似,都是用來查找所選元素的后代元素,但是find()方法能夠查找所有后代元素,而children()方法僅能夠查找子元素。
<script type=
"text/javascript"
>
$(
function
() {
$(
".wrapper"
).hover(
function
() {
$(
this
).find(
".test"
).text(
"www.nanaopearl.com
"
);
},
function
() {
$(
this
).find(
".test"
).text(
"www.nanaopearl.com
"
);
})
})
</script>