How to change class and id in JavaScript_javascript tips
It's className, not class
Note that JavaScript uses className to access the class attribute, because class is a reserved keyword, because in the future JavaScript may start to support classes like Java.
We encountered thorny details and browser differences when discussing the style attribute, which was like going through a stormy sea. The changes of class and id are like a calm oasis in the desert, where browsers live in harmony. Consider this example:
p {
color: #000000; /* black */
}
p.emphasis {
color: #cc0000; /* red */
}
Test
Initially, the paragraph has no class defined, so its font color It's black. However, a single line of JavaScript is enough to change its style:
document.getElementById('test').className = 'emphasis';
In an instant the text turns 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 returns to the default p{} rules.
For a practical example, take a look at "Limited length text input area". The counter has this structure and rendering style (the structure is dynamically generated by JavaScript, but that doesn't affect this example):
div.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 of as a counter to toomuch:
[Length-limited text input area, lines 20-23]
if (currentLength > maxLength)
this.relatedElement.className = 'toomuch';
else
this.relatedElement.className = '';
Now, the font of as counter changes in bold and red.
Change of id works almost exactly the same way:
p {
color: #000000; /* black */
}
p#emphasis {
color: #cc0000; /* red */
}
Test
document.getElementsByTagName('p')[0].id = 'emphasis';
The text of this paragraph turns red again. However, I recommend you not to change the id too much. In addition to being used as CSS hooks, they are also often used as JavaScript hooks, and changing them may have unspecified side effects.
Add class
Normally, you don’t set a new value for an element’s class, you just add a class. Because you don't want to remove any styles the element already has. Because CSS allows composite styles, the styles contained in the new class are added to the element without removing any CSS directives from the existing class.
The writeError() and removeError() functions in "Form Validation" are a good example. Generally I apply several classes to form fields because graphic designers often use two or even three widths for input fields. I want to add a special warning style when a form field contains an error, but I don't want to mess with the styles that the element already has. So, I can't simply overwrite the old class value, then I'll lose the width I've specified.
Look at this situation:
input.smaller {
width: 75px;
}
input.errorMessage {
border-color: #cc0000;
}
Initially, the width of the input box 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, which can be very confusing to the user.
Therefore, I added the errorMessage class:
[Form validation, lines 105~106]
function writeError(obj,message) {
obj.className = ' errorMessage';
This code gets the existing className and appends a new class after it, adding a space before it. This space separates the new class from any class values the object may already have. Now the input box has a red border as we expected, in addition to being 75px wide. The form field now has two classes applied, and the HTML looks like this:
Class name in Mozilla with a blank
You may notice removeError( ) There is no leading space when removing the value of class errorMessage. That's because of a browser bug. When you add errorMessage to a class that originally had no value, Mozilla removes the leading spaces. If we then execute replace(/ errorMessage/,''), Mozilla cannot remove the class because it cannot find the string errorMessage because the leading spaces are no longer there.
Remove class
Once the user fixes her error, the value of class errorMessage should be removed, but any original class, such as smaller, should not be affected. The removeError() function provides this function:
[Form validation, lines 119-120]
function removeError() {
this.className = this.className. replace(/errorMessage/,'');
It first gets the class of the element and then replaces the string 'errorMessage' with '' (a null character). errorMessage is taken from the value of class, but has no effect on other values. The form field loses its red border color, but still maintains a width of 75px.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



When logging into iTunesStore using AppleID, this error saying "This AppleID has not been used in iTunesStore" may be thrown on the screen. There are no error messages to worry about, you can fix them by following these solution sets. Fix 1 – Change Shipping Address The main reason why this prompt appears in iTunes Store is that you don’t have the correct address in your AppleID profile. Step 1 – First, open iPhone Settings on your iPhone. Step 2 – AppleID should be on top of all other settings. So, open it. Step 3 – Once there, open the “Payment & Shipping” option. Step 4 – Verify your access using Face ID. step

If you find event ID 55, 50, 140 or 98 in the Event Viewer of Windows 11/10, or encounter an error that the disk file system structure is damaged and cannot be used, please follow the guide below to resolve the issue. What does Event 55, File system structure on disk corrupted and unusable mean? At session 55, the file system structure on the Ntfs disk is corrupted and unusable. Please run the chkMSK utility on the volume. When NTFS is unable to write data to the transaction log, an error with event ID 55 is triggered, which will cause NTFS to fail to complete the operation unable to write the transaction data. This error usually occurs when the file system is corrupted, possibly due to the presence of bad sectors on the disk or the file system's inadequacy of the disk subsystem.

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

In Alibaba software, once you successfully register an account, the system will assign you a unique ID, which will serve as your identity on the platform. But for many users, they want to query their ID, but don't know how to do it. Then the editor of this website will bring you detailed introduction to the strategy steps below. I hope it can help you! Where can I find the answer to Alibaba ID: [Alibaba]-[My]. 1. First open the Alibaba software. After entering the homepage, we need to click [My] in the lower right corner; 2. Then after coming to the My page, we can see [id] at the top of the page; Alibaba Is the ID the same as Taobao? Alibaba ID and Taobao ID are different, but the two

Where can I check the Tencent Video ID? There is an exclusive ID in the Tencent Video APP, but most users do not know how to check the Tencent Video ID. Next is the graphic tutorial on how to check the Tencent Video ID brought by the editor for users who are interested. Users come and take a look! Tencent Video Usage Tutorial Where to check Tencent Video ID 1. First open the Tencent Video APP and enter the special area through [Personal Center] in the lower right corner of the main page; 2. Then enter the Personal Center page and select the [Settings] function; 3. Then go to Settings page, click [Exit Account] at the bottom; 4. Finally, you can view the exclusive ID number on the page shown below.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order
