Newcombe Newcombe - 3 months ago 9
HTML Question

Add class to an element if its content equals specified value

I'm trying to have a class added if an element is blank or has a value of zero.

The HTML is generated by the platform I'm using and cannot be adjusted without using scripts, so I'm restricted to JavaScript / jQuery and CSS to make the adjustments.

Here's what I have and I just can't quite get it.

HTML



<div class="Widget1001783 WidgetType23 microCart" id="w1001783_pnlDefaultBody">
<table width="100%">
<tbody>
<tr id="w1001783_trHeader">
<th colspan="2"> <span class="FormLabel" id="w1001783_lblCart">shopping cart</span> </th>
</tr>
<tr id="w1001783_trItems">
<td><span class="FormLabel" id="w1001783_lblItems">items:</span></td>
<td align="right"><span class="FormLabel" id="w1001783_lbdItems">0</span></td>
</tr>
</tbody>
</table>
</div>


CSS



.microCart tr:nth-of-type(2) td:last-child::after {
content: "♣";
}

.microCart.emptyCart tr:nth-of-type(2) td:last-child,
.emptyCart *::after {
content:"";
display:none;
}


jQuery



$(document).ready(function() {
if ($(".microCart tr:nth-of-type(2) td:last-child span").html("0"))
$(".microCart").addClass("emptyCart");
else ($(".microCart").removeClass("emptyCart"));
});

Answer

If you pass anything to html() function - then it sets that to the inner html of the element - see documentation. So in your example you're not comparing the html of the element to 0, rather you set the html value of the node to it. Which is why it doesn't work as you expected.

Mostly that's all what needs to be fixed.

The other thing is that usage of text() is better, as you're not interested in all the possible tags inside the element. The example is below.

function updateClass() {
  var $cart = $(".microCart");
  var text = $cart.find("tr:nth-of-type(2) td:last-child span").text().trim();
  if ((text == "0") || !text.length)
      $cart.addClass("emptyCart");
  else 
      $cart.removeClass("emptyCart");
}
.microCart tr:nth-of-type(2) td:last-child::after {
   content: "♣";
}

.microCart.emptyCart tr:nth-of-type(2) td:last-child,
.emptyCart *::after {
    content:"";
    display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Widget1001783 WidgetType23 microCart" id="w1001783_pnlDefaultBody">
    <table width="100%">
        <tbody>
            <tr id="w1001783_trHeader">
                <th colspan="2"> <span class="FormLabel" id="w1001783_lblCart">shopping cart</span> </th>
            </tr>
            <tr id="w1001783_trItems">
                <td><span class="FormLabel" id="w1001783_lblItems">items:</span></td>
                <td align="right"><span class="FormLabel" id="w1001783_lbdItems">0</span></td>
            </tr>
        </tbody>
    </table>
</div>

<input type="button" value="Set class" onclick="updateClass()"/>