JSFiddle - React, Tailwind, and code Playground
by nivas
HTML
<div class="parent">
This div must be hidden
</div>
<div class="parent">
This div must be visible
<div class="child">
child div
</div>
</div>
<input type="button" value="Jquery" id="byJQ"/>
<input type="button" value="Pure JS" id="byJS"/>
CSS
body
{
font-family: verdana, sans-serif;
font-size: .75em;
}
.parent
{
background-color: #DAFF9F;
padding: .5em;
margin: .5em;
}
.child
{
background-color: #FFEEBF;
padding: .5em;
margin: .5em;
}
JavaScript
//Pure JS
function hideJS()
{
//getElementsByClassName from @CMS's answer to the linked question
var parentDivs = getElementsByClassName(document, "parent");
for(var i=0; i<parentDivs.length; i++)
{
var children = getElementsByClassName(parentDivs[i], "child");
if(!children || children.length == 0)
{
parentDivs[i].style.display = "none";
}
}
}
//Jquery
$(document).ready( function()
{
$("#byJQ").click(function(){
$(".parent").each(function()
{
if($(this).children(".child").length == 0)
{
$(this).hide();
}
});
});
$("#byJS").click(hideJS);
});
//getElementsByClassName from http://stackoverflow.com/questions/1933602/#answer-1933623
function getElementsByClassName(node,classname)
{
if (node.getElementsByClassName)
{ // use native implementation if available
return node.getElementsByClassName(classname);
}
else
{
return (function getElementsByClass(searchClass,node)
{
if ( node == null )
node = document;
var classElements = [],
els = node.getElementsByTagName("*"),
elsLen = els.length,
pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;
for (i = 0, j = 0; i < elsLen; i++)
{
if ( pattern.test(els[i].className) )
{
classElements[j] = els[i];
j++;
}
}
return classElements;
})(classname, node);
}
}