简体   繁体   中英

jQuery: Returning the text from first-child or self

I am trying to get the text inside an element and I only want to get the text if it's inside the first-child of a placehoder div or if there are no childrent and it's only text inside.
So the two scenarios are:

<div id="wrap">text1</div>

and

<div id="wrap"><b>text1</b><b>text2</b></div>

So In both cases I want to get back "text1"
I know how to do it with 2 different queries but I am trying to unite them into one

$("#wrap :first-child").text()
$("#wrap").text()
$("#wrap :first-child").text() || $("#wrap").text() 

由于jquery选择器表达式按文档顺序给出结果,因此可以组合表达式。

$('#wrap :first-child, #wrap').filter(':last').text()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM