Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: selector (classname with space)

I'm trying to get a div which has "panel current" as classname. The problem is the space - how can I select it?

like image 380
Fuxi Avatar asked Jan 01 '10 12:01

Fuxi


People also ask

Can CSS selectors have spaces?

A space in a CSS selector has very special meaning. It means that the part of the selector that occurs right of the space is within (a child of) the part of the selector to the left. This doesn't apply to your second example, because it has no space.

Can class attribute have space?

The class name can't contain a space, but it can contain hyphens or underscores. Any tag can have multiple space-separated class names.

How do you select an element with multiple classes?

Use the getElementsByClassName method to get elements by multiple class names, e.g. document. getElementsByClassName('box green') . The method returns an array-like object containing all the elements that have all of the given class names.

Which one is the correct selector of jQuery for class box?

The . The jQuery . class selector finds elements with a specific class.


2 Answers

Class names can't have spaces in them. What you have there is two classes:

<div class="panel current"> 

This div has two classes: panel and current. That's easily selected:

$("div.panel.current")... 

That means select all divs that have class panel and class current.

like image 94
cletus Avatar answered Sep 20 '22 03:09

cletus


$('div').filter(function() {     return this.className == 'panel current'; }); 

OR

$("div[class='panel current']"); 

Use this if you need to match an element with an exact match of class names (including spaces)

The other posters are right, the DiV you posted has two class names: 'panel' and 'current'; If you want to select them both, use $('.panel.current').

This will also include elements like:

<div class="foo panel bar current"></div> 
like image 40
David Hellsing Avatar answered Sep 18 '22 03:09

David Hellsing