How to change the class and id in JavaScript _ javascript skills

Source: Internet
Author: User
JavaScript allows you to change the class or id of an element. After you change the style, the browser automatically updates the style of the element. Is className, not class

Note that JavaScript uses className to access the class attribute, because class is a reserved keyword, because JavaScript may begin to support classes like Java in the future.

When discussing style attributes, we encountered the trouble of difficult details and browser differences, just as we experienced a rough wave. The changes to the class and id are like an oasis of calm in the desert, where browsers get along in harmony. Think about this example:

P {

Color: #000000;/* black */

}

P. emphasis {

Color: # cc0000;/* red */

}

Test



Initially, the section does not define a class, so its font color is black. However, a line of JavaScript is enough to change its style:

Document. getElementById ('test'). className = 'memphasa ';

The text instantly becomes red. If you want to change it back, you can do the following:

Document. getElementById ('test'). className = '';

You have removed the style and the paragraph is restored to the default p {} rule.

For an example in practical application, let's look at the "limited text input area ". The counter has such a structure and rendering style (this structure is dynamically generated by JavaScript, but it does not affect this example ):

12/1250



P. counter {

Font-size: 80%;

Padding-left: 10px;

}

Span. toomuch {

Font-weight: 600;

Color: # cc0000;

}

When the script finds that the text entered by the user must have reached the maximum length, it modifies the class as the counter to toomuch:

[Limited text input area, 20th ~ 23 rows]

If (currentLength> maxLength)

This. relatedElement. className = 'toomuch ';

Else

This. relatedElement. className = '';

Now, the font of the counter is in bold and red.

Id changes work in almost the same way:

P {

Color: #000000;/* black */

}

P # emphasis {

Color: # cc0000;/* red */

}

Test



Document. getElementsByTagName ('P') [0]. id = 'phasis ';

The text in the paragraph turns red again. However, I suggest you do not change the id too much. In addition to CSS hooks, they are often used as JavaScript hooks. changing them may have uncertain side effects.

Add class

Generally, you do not set a new value for the class of an element, but simply add a class. Because you do not want to remove any styles that the element already has. Because CSS allows compound styles, the style contained in the new class is added to the element, and no CSS commands of the existing class are removed.

The writeError () and removeError () functions in form verification are good examples. In general, I will apply several classes to the form field, because the graphic designer often uses two or three widths for the input box. When a form field contains an error, I want to add a special warning style, but I do not want to disturb the style that the element already has. Therefore, I cannot simply overwrite the old class value, so that I will lose the specified width.

See the following situation:



Input. smaller {

Width: 75px;

}

Input. errorMessage {

Border-color: # cc0000;

}

At the beginning, the input box width is 75px. If the script sets the class to 'errormessage' and deletes the old value, the form field will get a red border, but also lose its width, in this case, users may be confused.

Therefore, I added the errorMessage class:

[Form Verification, 105th ~ 106 rows]

Function writeError (obj, message ){

Obj. className + = 'errormessage ';

This code gets the existing className, attaches a new class to it, and adds a space before it. This space separates the new class from the class values that any object may have. Now, in addition to the 75px width, the input box gets the red border as we wish. The form field now applies two classes. HTML is like this:



Class Name and blank in Mozilla

You may notice that there is no leading space when removeError () removes the class value errorMessage. That's because of a browser bug. When you add errorMessage to a class without a value, Mozilla deletes leading spaces. If we then execute replace (/errorMessage/, ''), Mozilla cannot remove the class and it cannot find the string errorMessage because the leading space is no longer there.

Remove class

Once the user corrected her error, the class value errorMessage should be removed, but any original class, such as smaller, should not be affected. The removeError () function provides the following functions:

[Form Verification, 119th ~ 120 rows]

Function removeError (){

This. className = this. className. replace (/errorMessage /,'');

It first obtains the class of the element and replaces the string 'errormessage' with ''(an empty character ). ErrorMessage is removed from the class value, but it does not affect other values. The form field loses the red border color, but still maintains the 75px width.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.