jonshariat
jonshariat

Reputation: 176

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, 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.

Upvotes: 0

Views: 296

Answers (4)

S L
S L

Reputation: 14318

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.

Upvotes: 1

jensgram
jensgram

Reputation: 31508

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.

Upvotes: 1

Laxman13
Laxman13

Reputation: 5211

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

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

Upvotes: 2

rsp
rsp

Reputation: 111336

Change:

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

to:

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

Upvotes: 2

Related Questions