简体   繁体   中英

get style property value using css()

<p class="pen" style="color:#000">abc</p>

.pen{
color:#333
}

In the above html and css, the inline style has greater precedence than the class, thus #000 will be used. But when I do $('.pen').css('color') , I get #333 . How can I get the color of the current style?

If you have two elements with the same class

<p class="pen" style="">abc</p>
<p class="pen" style="color:#000">abc</p>

and run,

$('.pen').css('color')

The output would b #333 or rgb(51,51,51) .; because the selector finds the first element matching. So this is the problem with your code - Multiple elements with class pen .

Fiddle


In case of single pen element or the order

<p class="pen" style="color:#000">abc</p>
<p class="pen" style="">abc</p>

the output is #000 .

Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM