Emerson Maningo
Emerson Maningo

Reputation: 2269

jQuery selector depending on the value of the span tag

Supposing I have this HTML:

<div id="mydiv">
<p>
<span>My first span</span>
</p>
<p>
<span>My second span</span>
</p>
<p>
<span>My third span</span>
</p>

My problem is that I'm appending HTML to the p tags:

$('#mydiv p').append('<img src="http://example.com/myimage.png">');

But I only want to append to the second p with the span tag text "My second span" (or any other p tags with their respective span text depending on my application). so this is the resulting HTML after appending:

<p>
<span>My second span</span><img src="http://example.com/myimage.png">
</p>

One limitation is that I cannot edit the original HTML sourcecode so I cannot assign class or ID selectors to them.

How would I revise my jQuery selectors to target a specific p with the specific span text? Thanks for any tips.

Upvotes: 0

Views: 155

Answers (4)

Hui Zheng
Hui Zheng

Reputation: 10224

This should work: $('#mydiv p:nth-child(2)') (i.e. select the second child with p tag of mydiv)

Surely you can select that element by hard-coded text, but I don't think that is a good idea.

Upvotes: 0

Sang Suantak
Sang Suantak

Reputation: 5265

Try this:

$('#mydiv p:eq(1)').append('<img src="http://example.com/myimage.png">');

Edit:

With your updated question, the selector suggested by Daveo's answer above should do it. However, in that case you need to use after instead of append:

$("#mydiv span:contains('My second span')").after('<img src="http://example.com/myimage.png">');

Upvotes: 0

charlietfl
charlietfl

Reputation: 171669

Assume from explanation you want this text specific. Can use :contains(text) selector.

var txt="My second span" ;
/* selector finds the span, parent() moves back up to "p" tag*/
$('#mydiv p span:contains('+txt+')').parent().append('<img ...>');

API reference: http://api.jquery.com/contains-selector/

Not clear if it has to be filtered to only second span containing this text

Upvotes: 0

Daveo
Daveo

Reputation: 19872

You can achieve this with the :contains() selector.

$("#mydiv span:contains('My second span')")

Upvotes: 2

Related Questions