Anyone Know What The Purpose of Tagging a Class with *[Class]

Why to use class= when I can use my own tag?

There are many advantages of using class.

  1. First of all, with class, we use css styles which gives a lot more configuration options than simple HTML tags.
  2. We give all the styles and formatting at one olace and just call the class everywhere we want to apply those, which in big projects like ERP, makes a big difference in code size.
  3. The css style is more compatible with latest versions of browsers and a lot of old HTML formatting and style tags are deprecated in latest versions of HTML.
  4. HTML tags behave differently under different browsers and different document modes. Where css will give same result everywhere.
  5. The css classes can be applied to all the relevant tags on page at once just by defining it somewhere at the top of page.

CSS selector for first element with class

This is one of the most well-known examples of authors misunderstanding how :first-child works. Introduced in CSS2, the :first-child pseudo-class represents the very first child of its parent. That's it. There's a very common misconception that it picks up whichever child element is the first to match the conditions specified by the rest of the compound selector. Due to the way selectors work (see here for an explanation), that is simply not true.

Selectors level 3 introduces a :first-of-type pseudo-class, which represents the first element among siblings of its element type. This answer explains, with illustrations, the difference between :first-child and :first-of-type. However, as with :first-child, it does not look at any other conditions or attributes. In HTML, the element type is represented by the tag name. In the question, that type is p.

Unfortunately, there is no similar :first-of-class pseudo-class for matching the first child element of a given class. At the time this answer was first posted, the newly published FPWD of Selectors level 4 introduced an :nth-match() pseudo-class, designed around existing selector mechanics as I mentioned in the first paragraph by adding a selector-list argument, through which you can supply the rest of the compound selector to get the desired filtering behavior. In recent years this functionality was subsumed into :nth-child() itself, with the selector list appearing as an optional second argument, to simplify things as well as averting the false impression that :nth-match() matched across the entire document (see the final note below).

While we await cross-browser support (seriously, it's been nearly 10 years, and there has only been a single implementation for the last 5 of those years), one workaround that Lea Verou and I developed independently (she did it first!) is to first apply your desired styles to all your elements with that class:

/* 
* Select all .red children of .home, including the first one,
* and give them a border.
*/
.home > .red {
border: 1px solid red;
}

... then "undo" the styles for elements with the class that come after the first one, using the general sibling combinator ~ in an overriding rule:

/* 
* Select all but the first .red child of .home,
* and remove the border from the previous rule.
*/
.home > .red ~ .red {
border: none;
}

Now only the first element with class="red" will have a border.

Here's an illustration of how the rules are applied:

.home > .red {
border: 1px solid red;
}

.home > .red ~ .red {
border: none;
}
<div class="home">
<span>blah</span> <!-- [1] -->
<p class="red">first</p> <!-- [2] -->
<p class="red">second</p> <!-- [3] -->
<p class="red">third</p> <!-- [3] -->
<p class="red">fourth</p> <!-- [3] -->
</div>

What is this CSS selector? [class*=span]

It's an attribute wildcard selector. In the sample you've given, it looks for any child element under .show-grid that has a class that CONTAINS span.

So would select the <strong> element in this example:

<div class="show-grid">
<strong class="span6">Blah blah</strong>
</div>

You can also do searches for 'begins with...'

div[class^="something"] { }

which would work on something like this:-

<div class="something-else-class"></div>

and 'ends with...'

div[class$="something"] { }

which would work on

<div class="you-are-something"></div>

Good references

  • CSS3 Attribute Selectors: Substring Matching
  • The 30 CSS Selectors you Must Memorize
  • W3C CSS3 Selectors

why do people use classes in html when they only have one of the element

If the site is in-development, this may mean that they plan to use more of that same item.

There isn’t really a difference otherwise, a class can be applied to multiple items, but an ID can only be applied to one item.

I use classes as a matter of personal preference, unless I plan to use JS with that (single) element, then it is easier for me to use an ID.

Get class name using jQuery

After getting the element as jQuery object via other means than its class, then

var className = $('#sidebar div:eq(14)').attr('class');

should do the trick. For the ID use .attr('id').

If you are inside an event handler or other jQuery method, where the element is the pure DOM node without wrapper, you can use:

this.className // for classes, and
this.id // for IDs

Both are standard DOM methods and well supported in all browsers.

Angular: conditional class with *ngClass

Angular version 2+ provides several ways to add classes conditionally:

type one

    [class.my_class] = "step === 'step1'"

type two

    [ngClass]="{'my_class': step === 'step1'}"

and multiple option:

    [ngClass]="{'my_class': step === 'step1', 'my_class2' : step === 'step2' }"

type three

    [ngClass]="{1 : 'my_class1', 2 : 'my_class2', 3 : 'my_class4'}[step]"

type four

    [ngClass]="step == 'step1' ? 'my_class1' : 'my_class2'"

You can find these examples on the documentation page

Mentioning the HTML TAG element before a CLASS or ID (Good or unnecessary CSS practice?)

It depends what you want to happen.

#content

will apply to everything with id="content", but

div#content

will only apply to a <div> with id="content".

This is usually more of an issue with classes since IDs should be unique across all elements on a page.

So the bottom line is, if you know the style information will only apply to HTML elements of a certain type, then include the element tag. This can stop styles from being unexpectedly applied to different elements with the same class (or ID, but that's naughty).

How can I find an element by CSS class with XPath?

This selector should work but will be more efficient if you replace it with your suited markup:

//*[contains(@class, 'Test')]

Or, since we know the sought element is a div:

//div[contains(@class, 'Test')]

But since this will also match cases like class="Testvalue" or class="newTest", @Tomalak's version provided in the comments is better:

//div[contains(concat(' ', @class, ' '), ' Test ')]

If you wished to be really certain that it will match correctly, you could also use the normalize-space function to clean up stray whitespace characters around the class name (as mentioned by @Terry):

//div[contains(concat(' ', normalize-space(@class), ' '), ' Test ')]

Note that in all these versions, the * should best be replaced by whatever element name you actually wish to match, unless you wish to search each and every element in the document for the given condition.

How can I remove all CSS classes using jQuery/JavaScript?

$("#item").removeClass();

Calling removeClass with no parameters will remove all of the item's classes.


You can also use (but it is not necessarily recommended. The correct way is the one above):

$("#item").removeAttr('class');
$("#item").attr('class', '');
$('#item')[0].className = '';

If you didn't have jQuery, then this would be pretty much your only option:

document.getElementById('item').className = '';


Related Topics



Leave a reply



Submit