0

I'm trying to change the class of a nested span element, when clicking a certain item. JSFiddle goes here.

HTML:

<div id="title_1" class="title">Title 1</div>
<span id="foo_1" class="foo">
    foo contents<br />
    <span class="bar">bar contents</span>
    <br /><br />
</span>

<div id="title_2" class="title">Title 2</div>
<span id="foo_2" class="foo">
    foo contents<br />
    <span class="bar">bar contents</span>
    <br /><br />
</span>

Changing the class of the first span is possible though $(this).nextAll('.foo:first').addClass('highlight'); like I'm doing in the current JSFiddle.

However I want to change the class of 'bar' element only.

Among some things of what I tried:

$(this).nextAll('.foo:first .bar:first').addClass('highlight');
$(this).nextAll('.foo .bar:first').addClass('highlight');
$(this).nextAll('.foo:first').nextAll('.bar:first').addClass('highlight');
$(this).next('.foo').next('.bar').addClass('highlight');

... all without success.

I think I'm missing something basic here. Can someone help me out?

3 Answers 3

1

Here you go: https://jsfiddle.net/nez0cvsm/

Just change nextAll() with next() (to access the span after the title) and then add .children() (to access the span inside the span). I used children instead of "find" supposing that inside that span there will be only another one.

Sign up to request clarification or add additional context in comments.

Comments

1

If you are planning to have more than one span and only want to select the ones with the bar class you can use the following:

$(this).next().children('.bar').addClass('highlight');

Example here (with extra span): https://jsfiddle.net/1ekrjqk1/

Comments

1

You can also use next and then find the element with class bar

$(this).next('.foo').find('.bar').addClass('highlight');

Demo: https://jsfiddle.net/yssusqq9/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.