I have the following element:
<div class="parent">
<div class="col">MyColumn</div>
</div>
I want to style the parent
class only if it contains a class with class col
I have the following element:
<div class="parent">
<div class="col">MyColumn</div>
</div>
I want to style the parent
class only if it contains a class with class col
Below are two options to do it using jQuery
:
Option 1
$('.parent').has('.col').addClass('style');
.style {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<div class="col">MyColumn</div>
</div>
Option 2
if ($(".col").parents(".parent").length == 1) {
// add style here
$(".parent").css({'background': "red"});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="parent">
<div class="col">MyColumn</div>
</div>
Threw together a fairly legacy compatible JavaScript version:
var parents = document.querySelectorAll('.parent')
for (var i = 0; i < parents.length; i++) {
for (var j = 0; j < parents[i].children.length; j++) {
if (hasClass(parents[i].children[j], 'col')) {
updateCss(parents[i])
}
}
}
function hasClass(element, className) {
return (' ' + element.className + ' ').indexOf(' ' + className+ ' ') > -1;
}
function updateCss (parent) {
// whatever you want to add here...
parent.style.color = 'red';
}
.parent {
margin: 15px;
outline: 1px dotted black;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>repl.it</title>
<link href="index.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="parent">
<div class="col">MyColumn</div>
</div>
<div class="parent">
<div class="something-else">not column</div>
<div class="col">MyColumn</div>
</div>
<div class="parent">
<div class="something-else">not column</div>
</div>
<script src="index.js"></script>
</body>
</html>
In JQuery you can use the :has
selector, like this:
$('.parent:has(.col)').css(/* your css */);
this is what I've come up with so far. what I'm trying to do is to spread the div's with class COL in the remaining space after the size specific col's.
it's still not perfect and needs a little tweaking, but a step in the right direction.
var mediaBase = parseFloat(8.33333);
$.each($("div.row"), function (index) {
var gens = 0;
var total = 0;
$.each($(this).find("div[class^='col']"), function (ii) {
if (total > 100) {
$(this).hide();
}
else {
if ($(this).attr("class").indexOf("-") > 0) {
let tmp = $(this).attr("class");
tmp = parseInt(tmp.slice(tmp.lastIndexOf("-") + 1));
total += parseFloat(mediaBase * tmp);
}
else {
gens++;
}
}
});
if (gens > 0 && total < 100) {
let val = (100 - total) / gens;
if (total === 0) {
val = 100 / gens;
}
$(this).find("div.col").css("width", val.toString() + "%");
}
});