davidchoo12
davidchoo12

Reputation: 1321

How to select an specific element by a css class, but not other elements?

So I want to select the <div> element with the class .thisClass, but not any other elements with class of .thisClass:

<div class="thisClass"></div>
<p class="thisClass"></p>

Upvotes: 0

Views: 1154

Answers (3)

sergdenisov
sergdenisov

Reputation: 8572

CSS Selector by class name and tag: div.thisClass { ... }:

div.thisClass {
    background-color: red;
}
<div class="thisClass">thisClass (div)</div>
<p class="thisClass">thisClass (p)</p>

But this is a bad way to write selectors:

Don’t qualify class rules with tag names

The previous concept also applies here. Though classes can be used many times on the same page, they are still more unique than a tag.

One convention you can use is to include the tag name in the class name. However, this may cost some flexibility; if design changes are made to the tag, the class names must be changed as well. (It’s best to choose strictly semantic names, as such flexibility is one of the aims of separate stylesheets.)

BAD
treecell.indented {…}

GOOD
.treecell-indented {…}

BEST
.hierarchy-deep {…}

Upvotes: 4

RIYAJ KHAN
RIYAJ KHAN

Reputation: 15292

Using JavaScript

document.querySelector('div.thisClass')

Using jQuery

$("div.thisClass")

Using CSS:

<style>
    div.thisClass{}
</style>

Upvotes: 2

Shashank
Shashank

Reputation: 2060

The following code illustrates how to select the first class from the list of classes in both CSS and Javascript.

CSS

.thisClass:first-child {
  /*css property*/
}

JAVASCRIPT:

var divElement = document.getElementsByClassName('thisClass')[0];

Upvotes: -1

Related Questions