KyleD KyleD - 6 months ago 11
Javascript Question

JQuery: Not targeting element

Using JQuery I want to target an element which has the same

class
as the
body
. This is what I have so far:

var bodyClass = $('body').attr("class");

if($('#productnav .container ul li').hasClass(bodyClass)) {
alert(bodyClass);

var thetab = $('#productnav .container ul' + bodyClass);
$(thetab).addClass("active");
}


The alert gets fired so there is clearly a
li
that has the same class. The problem is that I cannot seem to target that specific
li
.

The HTML

<div id="productnav">
<div class="container">
<ul>
<li class="accelerators" data-slide="0"><a class="active" href="/product-types/accelerators">
<span style="font-size: 11px;">Accelerators</span>
</a></li>
<li class="redispersible-powder-polymers" data-slide="1"><a href="/product-types/redispersible-powder-polymers">
<span style="font-size: 11px;">Redispersible Powder Polymers</span>
</a></li>
<li class="superplasticisers" data-slide="2"><a href="/product-types/superplasticisers">
<span style="font-size: 11px;">Super- plasticisers</span>
</a></li>
<li class="lightweight-fillers" data-slide="3"><a href="/product-types/lightweight-fillers">
<span style="font-size: 11px;">Lightwight Fillers</span>
</a></li>
<li class="cellulose-ethers" data-slide="4"><a href="/product-types/cellulose-ethers">
<span style="font-size: 11px;">Cellulose Ethers</span>
</a></li>
<li class="fibres" data-slide="5"><a href="/product-types/fibres">
<span style="font-size: 11px;">Fibres</span>
</a></li>
<li class="retarders" data-slide="6"><a href="/product-types/retarders">
<span style="font-size: 11px;">Retarders</span>
</a></li>
<li class="power-air-entrainers" data-slide="7"><a href="/product-types/power-air-entrainers">
<span style="font-size: 11px;">Power Air Entrainers</span>
</a></li>
<li class="poraver-x" data-slide="8"><a href="/product-types/poraver-x">
<span style="font-size: 11px;">Poraver X</span>
</a></li>
</ul>
</div>
</div>


Any ideas?

T J T J
Answer

You are missing a .

var thetab = $('#productnav .container ul .' + bodyClass);
//----------------------------------------^
$(thetab).addClass("active");