user4061223
user4061223

Reputation:

How to edit the CSS of a div that does not contain a H1 tag?

There are two divs:

<div class="test">
<h1>This is a test</h1>
<p>Welcome to the test</p>
</div>

<div class="test">
<p>Welcome to the test</p>
</div>

As you can see, there are two divs which are in the same class however, one div has a H1 tag and the other div does not.

CSS:

.test {
font-size: 20px;
color: #fff
}

Above shows the CSS for the div test.

What I would like to do is apply additional CSS to the div that does not contain a H1 tag.

If div contains a H1 tag:

If div does NOT contain a H1 tag:

font-size: 30px;

Upvotes: 2

Views: 106

Answers (2)

AmmarCSE
AmmarCSE

Reputation: 30597

$('.test:not(:has(h1))').css('font-size', '30px');
.test {
font-size: 20px;
color: #000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="test">
<h1>This is a test</h1>
<p>Welcome to the test</p>
</div>

<div class="test">
<p>Welcome to the test</p>
</div>

You can use a selector with :not and :has like

$('.test:not(:has(h1))').css('font-size', '30px');

Upvotes: 4

Sean Stopnik
Sean Stopnik

Reputation: 1868

Not really the best way of doing things, but if you CANNOT edit the html, then you can target the CSS by doing:

http://jsfiddle.net/42amv1xj/

.test {
  font-size: 30px;
  color: #fff;
}

.test h1,
h1 ~ p {
    font-size: 20px;
}

This is really wonky though!

Upvotes: 2

Related Questions