Qchmqs
Qchmqs

Reputation: 1805

How do I target an <a> inside a <div>?

I have this code : http://jsfiddle.net/Qchmqs/BSKrG/

<div class="step"><-- this is darned wrong
    <div id="step2"><a>Darn</a></div>
    <div id="step2"><a>Darn</a></div>
    <div id="step2"><a>Darn</a></div>
</div>
<div class="step"><-- this works fine
    <div id="step2"><a>Darn</a>
    <a>Darn</a>
    <a>Darn</a></div>
</div>

The first block is three links inside three separate divs inside a surrounding div

The bottom block has the links inside one parent div

I am trying to change the background of an active link, but it won't turn off in the upper block.

The script works well with the bottom links but not working as expected with the upper ones

PS : The active class should be toggled only from the Links i have a lot of other scripts in the page that uses the .active links from this list.

Upvotes: 1

Views: 83

Answers (4)

mpw
mpw

Reputation: 180

Using radio inputs you can create this effect without any JS at all, which degrades gracefully from its intended appearance (a red backgrounded "damn") to damn with radios next to it (sending the same information). ironically, this example at JSfiddle: http://jsfiddle.net/YvQdj/

My memory is a bit fuzzy, but I'm pretty sure this doesn't work in older versions of IE without some finagling.

Upvotes: 0

Blazemonger
Blazemonger

Reputation: 92963

For starters, do what JamesJohnson said and remove the multiple IDs. They can only cause you problems down the road.

In the upper links, the a tags aren't siblings because you put each one in its own div. So you need to do this to remove classes from the other as:

$(this).parent().siblings('div').children('a').removeClass('active');

http://jsfiddle.net/mblase75/BSKrG/1/

Unfortunately, that breaks the functionality on the lower links. You can achieve success in both places by adding andSelf to the parent siblings:

$(this).parent().siblings('div').andSelf().children('a').removeClass('active');

http://jsfiddle.net/mblase75/BSKrG/2/

Upvotes: 2

RSM
RSM

Reputation: 15118

maybe this:

<div class="step">
    <div id="step2"><a>Damn</a>
    <a>Damn</a>
    <a>Damn</a></div>
</div>
<div class="step">
    <div id="step2"><a>Damn</a>
    <a>Damn</a>
    <a>Damn</a></div>
</div>

Upvotes: 0

James Johnson
James Johnson

Reputation: 46067

It's not working on the upper ones because you're assigning the same id to the divs. You should probably use the class attribute instead:

<div class="step2"><a>Damn</a></div>
<div class="step2"><a>Damn</a></div>
<div class="step2"><a>Damn</a></div>

After making the above changes, you should be able to do this:

$(".step2 a").text("Hello World!");

Upvotes: 1

Related Questions