开发者

How can a CSS id style be accessed in jquery?

I am new to jquery and cannot find out how to add a CSS id to a page element.

For example开发者_Python百科, here are the inline CSS stlyes:

#main h2 {
background: url(open.png) no-repeat 0% 10%;
padding-left: 20px;
cursor: pointer;
}
#main h2.close {
background-image: url(close.png);
}
#main h2.highlight {
color: red;
font-weight: bold;
text-transform: uppercase;
}

and here is the jquery I attempted:

$(document).ready(function() {
$("h2").addClass('#main h2.highlight');

It works of course with classes but I cannot figure out how to get the styles onto the h2 tag.


Change:

$("h2").addClass('#main h2.highlight');

to:

$("h2").addClass('highlight');


If you want to add the class "highlight" to the h2 tags you could do it like this:

$("h2").addClass('highlight');


On a limp here, but:

$('#main h2').addClass('highlight');

Will add the highlight class to <h2> elements within (descendants of) the element with ID main, effectively making the <h2> element(s) match the rule #main h2.highlight. Is that the objective? If not, please ignore.


Use css selectors . for class and # for id in jQuery function $('(css-selector)(name)') for selecting.

$("h2").addClass('highlight');

This will select h2 element and add class highlight to h2 element

You cannot add assign id to elements (only to one element), since id is supposed to be unique. If you have only one h2 element then

  1. First select h2 with $('h2')

  2. Assign attribute with attr function $('h2').attr('id','someid'). However it is not recommended.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜