hazertazer
hazertazer

Reputation: 1

I am trying to target/select elements in a different parent with CSS

Take a look at the code below...

As you can see the 'HAZEL(NUT)' and 'HASSEL(NØD)' has a different parent to the checkbox. Which is why I think the checkbox works for the font-weight part, but doesn't work for selecting #hazelnut or #hasselnod. If anyone could help me with the correct selector for #hazelnut and #hasselnod I would be very grateful.

Hope this is clear, I'm quite a newbie to HTML and CSS, so have trouble explaining what I mean sometimes!

HTML here:

<div class="container" id="lang">
<input type="radio" id="english" name="language" value="english" checked="checked" /> 
<input type="radio" id="dansk" name="language" value="dansk" />
<ul>
<label for="english"><li id="en">ENGLISH</li></label>
<label for="dansk"><li id="dk">DANSK</li></label>
</ul> 
</div>

<div class="container" id="myname">
<h1 id="hazelnut">HAZEL<br>(NUT)</h1>
<h1 id="hasselnod">HASSEL<br>(NØD)</h1>
</div>

CSS here:

#dansk:checked ~ * #dk {
    font-weight: 700; 
}

#dansk:checked ~ * #en {
    cursor: pointer;
}

#dansk:checked * #hazelnut {
    display: none;
}

#english:checked ~ * #en {
    font-weight: 700; 
}

#english:checked ~ * #dk {
    cursor: pointer;
}

#english:checked * #hasselnod {
    display: none; 
}

Many thanks!

Upvotes: 0

Views: 34

Answers (2)

Kevin Vess
Kevin Vess

Reputation: 331

To target elements in a different parent, I think you need to use jQuery:

$("#lang input").change(function () {
    var lang = $(this).val();
    if(lang == 'dansk') {
        $('#hazelnut').hide();
        $('#hasselnod').show();
    } else {
        $('#hazelnut').show();
        $('#hasselnod').hide();
    }
});

Check out this fiddle: http://jsfiddle.net/X3ZtK/

Upvotes: 0

TastySpaceApple
TastySpaceApple

Reputation: 3185

In CSS, for the ~ selector to work, the elements must have the same parent. As I see it, I'm afraid you'll have to involve some javascript in here.

What I'd do, is have the radio buttons change a data attribute of #lang, so it would be transparent to the css:

<div id="lang" data-value="en">

and then use the following css rules:

/*when #myname is preceded by #lang with data-value attribute 'en',
 select direct child #hasselnod */
#lang[data-value='en'] ~ #myname > #hasselnod {
    /* and set its display to none*/
    display: none; 
}

Now, we'll need the javascript to change the data-value attribute of #lang. Look at the onclick function in the following snippet:

<input type="radio" id="dansk" name="language" value="dansk"
      onclick="this.parentNode.setAttribute('data-value', 'da')" />

Check out this fiddle: http://jsfiddle.net/wkL7q/2/

Upvotes: 1

Related Questions