The first step to achieving this is by creating a function, and calling the function in the onclick attribute, for example: Especially on larger applications, more maintainable code is achieved by separating HTML markup from JavaScript interaction logic. Whilst it is possible to write JavaScript directly inside the HTML event attributes (such as onclick="this.className =' M圜lass'") this is not recommended behaviour. # Assigning these actions to onclick events: The same regex used above for removing a class can also be used as a check as to whether a particular class exists: if ( document.getElementById("MyElement").className.match(/(?:^|\s)M圜lass(?!\S)/) ) To check if a class is already applied to an element: The g flag tells the replace to repeat as required, in case the class name has been added multiple times. # Ensures there is no non-space character following (?!\S) # Negative lookahead to verify the above is the whole classname M圜lass # The literal text for the classname to remove * Code wrapped for readability - above is all one statement */Īn explanation of this regex is as follows: (?:^|\s) # Match the start of the string or any single whitespace character To remove a single class to an element, without affecting other potential classes, a simple regex replace is required: document.getElementById("MyElement").className =ĭocument.getElementById("MyElement").className.replace To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so: document.getElementById("MyElement").className = " M圜lass" (You can use a space-delimited list to apply multiple classes.) To add an additional class to an element: To replace all existing classes with one or more new classes, set the className attribute: document.getElementById("MyElement").className = "M圜lass" The standard JavaScript way to select an element is using document.getElementById("Id"), which is what the following examples use - you can of course obtain elements in other ways, and in the right situation may simply use this instead - however, going into detail on this is beyond the scope of the answer. It is, though, getting more and more supported. Unfortunately, these do not work in Internet Explorer prior to v10, though there is a shim to add support for it to IE8 and IE9, available from this page. If ( document.getElementById("MyElement").ntains('M圜lass') )ĭocument.getElementById("MyElement").classList.toggle('M圜lass') Modern browsers have added classList which provides methods to make it easier to manipulate classes without needing a library: document.getElementById("MyElement").classList.add('M圜lass') ĭocument.getElementById("MyElement").classList.remove('M圜lass') Modern HTML5 Techniques for changing classes
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |