最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery: Returning the text from first-child or self - Stack Overflow

programmeradmin5浏览0评论

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()

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()
Share Improve this question asked May 8, 2009 at 11:03 duckyflipduckyflip 16.5k5 gold badges35 silver badges35 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7
$("#wrap :first-child").text() || $("#wrap").text() 

As jquery selector expressions give results in document order, the expressions can be bined.

$('#wrap :first-child, #wrap').filter(':last').text()
发布评论

评论列表(0)

  1. 暂无评论