Steggie Steggie - 4 months ago 16
CSS Question

Show span if DIV hasClass

I'm beating myself over the head with this one. I don't know what's doing on. It's pretty simple but it just doesn't work. I want to show a

span
item when a
div
has a
class
. Yup, basic, but I can't get it to work.

Here is my HTML with the class
add-product


<div id="ot-pr" class="status-publish has-post-thumbnail hentry add-product">
<span class="arrow">Testing</span>
</div>


And this is the JavaScript

$(document).ready(function($){
if($("#ot-pr").hasClass('add-product')){
$(".arrow").show();
}
else {
$(".arrow").hide();
}
});


Here is the CSS of the
.arrow


.arrow {
display: none;
width: 0; height: 0;
line-height: 0;
border-right: 16px solid transparent;
border-top: 10px solid #c8c8c8;
top: 60px;
right: 0;
position: absolute;
}


What have I tried, adding a
find(span)
and add
else if
:

$(document).ready(function(){
if($("#ot-pr").hasClass('add-product')){
$(".arrow").find('span').show();
}
else if {
$(".arrow").hide();
}
});


Both separate or together don't work. Why isn't this working. This should be basic right?! I get no console errors and
jQuery.js
as been added to the page. All other scripts work just fine.

Answer

There's no need for JS here, you can achieve this in CSS alone:

.arrow {
  display: none;    
  /* simplified CSS for the example */
}
div.add-product .arrow {
  display: block;
}
<div id="ot-pr" class="status-publish has-post-thumbnail hentry add-product">
  <span class="arrow">arrow 1</span>
</div>

<div id="ot-pr" class="status-publish has-post-thumbnail hentry add-product">
  <span class="arrow">arrow 2</span>
</div>

<!-- not visible -->
<div id="ot-pr" class="status-publish has-post-thumbnail hentry">
  <span class="arrow">arrow 3</span>
</div>