user1124378
user1124378

Reputation:

Finding specific elements with jQuery

I have the following markup.

<h6>Brand</h6>

<ul>
    <li>Orange</li>
    <li>Black</li>
    <li>Green</li>
</ul>

<h6>Colour</h6>

<ul>
    <li>Green</li>
    <li>Blue</li>
    <li>Black</li>
    <li>Orange</li>
</ul>

I am unable to change or physically add into this markup, so hence trying to manipulate with jQuery.

What I want to achieve from this is to be able to change the word Black to Purple. But only the word Black that appears after the H6 containing "Colour"

I have this so far:

$("h6:contains('Colour'):.jqueryCheck:contains('Black')").html("Purple");

This however does not work... Why not?

Upvotes: 7

Views: 175

Answers (4)

Rafay
Rafay

Reputation: 31033

Try using the adjacent selector:

$("h6:contains('Colour')+ ul li:contains('Black')").text('Purple');

See this DEMO.

Upvotes: 5

jfriend00
jfriend00

Reputation: 707328

You can use something like this:

$("h6:contains('Colour')").next().find("li:contains('Black')").text('Purple');​

This finds the appropriate <h6> that contains "Colour", then advances to the next sibling (which is the <ul> tag, then inside that <ul>, it finds an <li> that contains "Black" and changes that text to "Purple".

You can see it work here: http://jsfiddle.net/jfriend00/rdSzC/

Upvotes: 5

shaunsantacruz
shaunsantacruz

Reputation: 8930

$('h6:contains("Colour")').next('ul').children('li:contains("Black")').text("Purple");

Fiddle

Upvotes: 2

gen_Eric
gen_Eric

Reputation: 227240

$("h6:contains('Colour')").next('ul').children("li:contains('Black')").html("Purple");

Or all as one selector string:

$("h6:contains('Colour') + ul li:contains('Black')").html("Purple");

Upvotes: 12

Related Questions