Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use setAttribute to modify css style in js

Shulou Source: shulou.com Published: 2022-06-03 16:31:39 09月25日 Update

Xiaobian to share with you how js use setAttribute to modify css style, I believe most people still do not know how to share this article for your reference, I hope you have a lot of harvest after reading this article, let's go to understand it together!

In JavaScript, css styles can be modified by classes using the setAttribute() method.

description

The setAttribute() method adds the specified attribute and assigns it the specified value.

If the specified attribute already exists, only set/change the value.

syntax

element.setAttribute(attributename,attributevalue)

parameters

attributename String Required. The name of the attribute you want to add.

attributevalue String Required. The attribute value you want to add.

examples

var testNode = document.getElementsByClassName("test")[0]; var cssTextBtn = document.getElementsByClassName("cssText")[0]; var attributeBtn = document.getElementsByClassName("setAttribute")[0]; var stylesheetBtn = document.getElementsByClassName("stylesheet")[0]; // 1. Change style: stylesheetBtn.addEventListener('click', function(e) { var stylesheet = document.styleSheets[0]; stylesheet.cssRules[0].style.backgroundColor = "green"; }, false); // 2. Modify the style content of a particular element node cssTextBtn.addEventListener('click', function(e) { testNode.style.cssText = "width: 300px; background-color: red; height: 200px;" testNode.style.border = "1px solid black" }, true); // 3. Modify style attribute values via setAttribute attributeBtn.addEventListener('click', function(e) { testNode.setAttribute('style', 'width: 400px; background-color: yellow; height: 300px;') }, false) The above is "js how to use setAttribute to modify css style" All the contents of this article, thank you for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to the industry information channel!

Tags: Attributes styles content articles methods not much elements parameters names most instances more knowledge nodes industry grammar information information channels channels references Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Apple Xiaomi OPPO Reno macOS vpn