Css get class name

HTML DOM Element className

The className property sets or returns an element’s class attribute.

See Also:

Syntax

Return the className property:

Set the className property:

Property Values

Value Description
class The class name(s) of an element.
Separate multiple classes with spaces, like «test demo».

Return Value

More Examples

Get the class attribute of the first element (if any):

Get a class attribute with multiple classes:

Overwrite an existing class attribute with a new one:

To add new classes, without overwriting existing values, add a space and the new classes:

if «myDIV» has a «myStyle» class, change the font size:

const elem = document.getElementById(«myDIV»);

if (elem.className == «mystyle») <
elem.style.fontSize = «30px»;
>

If you scroll 50 pixels from the top of this page, the class «test» is added:

function myFunction() if (document.body.scrollTop > 50) document.getElementById(«myP»).className = «test»;
> else document.getElementById(«myP»).className = «»;
>
>

Browser Support

element.className is supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Get css class name inside css

I need to build an xml mapping of all css classes / ids, and doing it manually is very tedious for css files that contain thousands of styles. From memory there were some quirks in older IE around sheets and rules but right now it evades me… Solution 3: In my case, i need all class names (there are selectors which is start with «.icon-» ) in icons.css for listing all defined font icons.

How to get names of css classes of an element

I have to check if an element was selected. The only way I can do it is to watch if an additional css class «selected» was added to this element.

, click: Select, attr: < id: Id >, event: < mouseover: OnMouseOver, mouseout: OnMouseOut, touchstart: OnTouchClick >" > When I select it it looks like:
, click: Select, attr: < id: Id >, event: < mouseover: OnMouseOver, mouseout: OnMouseOut, touchstart: OnTouchClick >" > The css class "selected" is added. And I need to check if it was added or not. I use the next code:
string classes = element.GetAttribute("class"); 

But unfortunately it returns only the first class «b-wide-option» and don’t return the second which I actually need.

 element.getAttribute("className"); 

Hope this will help you to solve problem

getElementsByClassName('foo') 
var className = $('.b-wide-option').attr('class'); 

or u can also use .hasClass() function.

var className = $('.b-wide-option').attr('class'); if($('.b-wide-option').hasClass('selected')) < //write your code >

You can get the class names by this:

element.Attributes["class"].ToString(); 

I’m so sorry guys! I’ve just checked another element, my fault! The simple code as element.getAttribute(«className»); and element.getAttribute(«class»); works perfect, indeed!)

I wish moderator delited this question, I»m sorry.

Apply CSS rules to a nested class inside a div, You use. #main_text .title < /* Properties */ >If you just put a space between the selectors, styles will apply to all children (and children of children) of the first. So in this case, any child element of #main_text with the class name title. If you use > instead of a space, it will only select the direct child of the element, …

Getting the names of all classes / ids contained within a css file?

Is there a way, or a tool, which can be used to get a list of the names of all the classes / ids contained within a css file?

I need to build an xml mapping of all css classes / ids, and doing it manually is very tedious for css files that contain thousands of styles.

  1. Include your css file into any html file.
  2. In console execute the following code: Array.prototype.forEach.call(document.styleSheets[0].cssrules,function(a))
  3. In the console will be the listing of all css tags used in your stylesheet.

You can iterate over document.styleSheets to get each style sheet, then iterate over the rules to find everything that matches a class or ID selector. The following is a simplistic approach that provides a general approach, the regular expressions to get the classes and IDs from the rules needs more work.

function getClassesAndIds() < var sheet, sheets = document.styleSheets; var rule, rules; var classes = []; var ids = []; var temp; for (var i=0, iLen=sheets.length; i// Get the IDs temp = rule.cssText.match(/\#\w+/g); if (temp) < ids.push.apply(ids, temp); >> > // Return an array of the class and ID arrays return [classes,ids]; // or as an object // return ; > window.onload = function() < console.log(getClassesAndIds()); >; 

From memory there were some quirks in older IE around sheets and rules but right now it evades me…

In my case, i need all class names (there are selectors which is start with «.icon-» ) in icons.css for listing all defined font icons.

const = Object.values(document.styleSheets) .find(sheet => Object.values(sheet.cssRules).find(rule => (rule.selectorText || '').match(/^.icon/) ) ) || > console.log(Object.values(cssRules).map(i => i.selectorText)) 

How to extract class names from a CSS selector?, With node-css-selector-parser, we can parse a CSS selector and based on a result type analyze class names used with a dot (e.g. .myclass) and class names used inside the attribute selector (e.g. [class*=test] ):

CSS: how to get class inside class

I am making a dropdown on hover, but I have a problem with CSS. I have class inside class inside a div etc. The problem is that the dropdown list doesn’t show. I think that I am doing something wrong with CSS selectors.

#header .row-2 < height:51px; >#header .row-2 ul < width:100%; overflow:hidden; >#header .row-2 ul li < float:left; font-size:20px; line-height:2.4em; margin-right:5px; background-color:#000; >#header .row-2 ul li.last < margin-right:0; >#header .row-2 ul li a < text-decoration:none; color:#f0f0f0;width:184px; height:56px;float:left; background-image:url(images/nav-bg.gif);b ackground-repeat:no-repeat; background-position:0 0; text-align:center; >#header .row-2 ul li a:hover, #header .row-2 ul li a.active < color:#d72a18; background-image:url(images/nav-act.gif); >/*Dropdown*/ #header .row-2 ul li div.button < height: 32px; width: 184px; margin: auto; >#header .row-2 ul li div.button ul, li < margin: 0; padding: 0; list-style: none; >#header .row-2 ul li div.button ul .file_menu < display: none; width: 300px; border: 1px solid #1c1c1c; >#header .row-2 ul li div.button ul.file_menu li < background-color: #302f2f; >#header .row-2 ul li div.button ul .file_menu li a < color:#FFFFFF; text-decoration:none; padding:10px; display:block; >#header .row-2 ul li div.button ul .file_menu li a:hover
#slogan < width:100%; height:auto; position:relative; background:url(images/banner-bg.gif) no-repeat left top; color:#1d1d1d >#slogan .image < position:absolute; right:-30px; top:-11px; z-index:100; width:100%; height:auto; overflow: hidden; background:url(images/banner-img.png) no-repeat left top >#slogan p < margin-bottom:23px >#slogan .inside < padding: 0 0 25px; width:939px >#page1 #content .box < margin:0 >#page1 #header .row-2 ul li a < height:56px >#page1 #header .row-2 ul li.last a:hover < position:relative;z-index:2 >.slideshow < position:relative; width:500px; height:332px; >.slideshow img

NOTE: I just added slideshow CSS, that i think is overwriting dropdown Thank You,

There are a lot of things I would do differently with how you’ve got your CSS laid out, but if you’re looking for a simple answer, use the > child selector instead of just a space in order to select only those lists that are in your row-2 class. For example,

    elements whose parent is a .row-2 element, which seems to be what you’re looking for.

CSS property value from class name, Nowdays you can use CSS variable inside a style attribute instead generating a specific class: Custom properties (sometimes referred to as CSS variables or cascading variables) are entities defined by CSS authors that contain specific values to be reused throughout a document.

Источник

Element.className

Свойство className отвечает за значение атрибута class элемента.

Примечание: Кстати, у className есть большой брат. Его зовут element.classList — более мощный и функциональный метод для работы с классами элемента.

Синтаксис

var cName = elem.className; elem.className = cName;
  • cName — строка. Если нужно указать несколько классов, они указываются через пробел.

Пример

var elm = document.querySelector("div"); alert(elm.className); //"booble example" elm.className = "class1 class2 class3"; alert(elm.className); //"class1 class2 class3" 

Примечание: ##### Примечание:Свойство получило необычное название className из-за того, что во многих языках, работающих с DOM, слово class является зарезервированным*.*

Поддержка браузерами

BCD tables only load in the browser

Спецификация

Смотрите также

Found a content problem with this page?

This page was last modified on 7 нояб. 2022 г. by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Получить класс CSS элемента с помощью JavaScript/jQuery

В этом посте мы обсудим, как получить класс CSS элемента с помощью JavaScript и jQuery.

1. Использование jQuery

Вы можете получить значение class атрибут с использованием jQuery .attr() метод.

JS

CSS

HTML

В качестве альтернативы вы можете использовать jQuery .prop() метод.

JS

CSS

HTML

2. Использование JavaScript

В простом JavaScript вы можете использовать className свойство, чтобы получить значение class атрибут указанного элемента.

JS

CSS

HTML

В современных браузерах вы можете получить значение className как:

JS

CSS

HTML

Вот и все, что касается получения CSS-класса элемента с помощью JavaScript и jQuery.

Средний рейтинг 4.68 /5. Подсчет голосов: 25

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

Этот веб-сайт использует файлы cookie. Используя этот сайт, вы соглашаетесь с использованием файлов cookie, нашей политикой, условиями авторского права и другими условиями. Читайте наши Политика конфиденциальности. Понятно

Источник

Class selectors

The CSS class selector matches elements based on the contents of their class attribute.

Syntax

.class_name  style properties > 

Note that this is equivalent to the following attribute selector :

[class~=class_name]  style properties > 

Examples

CSS

.red  color: #f33; > .yellow-bg  background: #ffa; > .fancy  font-weight: bold; text-shadow: 4px 4px 3px #77f; > 

HTML

p class="red">This paragraph has red text.p> p class="red yellow-bg"> This paragraph has red text and a yellow background. p> p class="red fancy">This paragraph has red text and "fancy" styling.p> p>This is just a regular paragraph.p> 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jul 22, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Читайте также:  Java get classes classloader
Оцените статью