SaiBand
SaiBand

Reputation: 5375

how to find the text of an element in jquery

Hello I have html markup like this:

<div class="expandNode expand">
<input id="100" type="checkbox" value="100" data-parent="">
<span>Office/Commercial</span>
</div>

In the console when I do $('#100') I get this:

[<input id=​"100" type=​"checkbox" value=​"100" data-parent>​]

What I need is the text within the span i.e. Office/Commercial.

How can I do this?

Upvotes: 1

Views: 52

Answers (3)

Roko C. Buljan
Roko C. Buljan

Reputation: 206669

Try with:

$('#100').next('span').text(); 

Or like:

$('.expandNode span').text();   // not suggested

Theremore the input tag needs to be closed and still I don't suggest to use numbers for ID elements ( < HTML5 )

A more flexible and future-proof way to achieve the same would be:

$('#100').closest('.expandNode').find('span').text();

Additionally, if you're sure there'll be only ONE <span> inside the parent element you can go for:

$('#100').siblings('span').text(); 

That way you don't have to rely on span be the immediate .next() element.

Upvotes: 4

karancan
karancan

Reputation: 2162

You could modify your span to give it an ID or class (OPTIONAL):

<span class="expand-span">Office/Commercial</span>

Then use this jQuery code to find it:

$('.expandNode').children('.expand-span');

If you don't want to give your span a class or ID, you can use:

$('.expandNode').children('span');

Upvotes: 0

Sylvain
Sylvain

Reputation: 3873

Try this :

$("#100").next('span').text();

Upvotes: 0

Related Questions