Home javascript How to change a property of a class using js?

How to change a property of a class using js?

Author

Date

Category

There is a div with the class mystyle . The class has a property margin how can I change it using regular js or jquery?

. mystyle, .mystyle ul {
 margin: 0;
} 
& lt; div class = "mystyle" & gt;
 & lt; ul & gt;
  & lt; li & gt; Example & lt; / li & gt;
 & lt; / ul & gt;
& lt; / div & gt; 

Answer 1, authority 100%

If you need to change in all elements of this class:

$ ('. mystyle'). css ('margin', '10px')

If you need to change directly in the styles:

$ (function () {
 var ss = document.styleSheets [0];
 var rules = ss.cssRules || ss.rules;
 var h1Rule = null;
 for (var i = 0; i & lt; rules.length; i ++) {
  var rule = rules [i];
  if (/ (^ |,) * \. mystyle * (, | $) / i.test (rule.selectorText)) {
   h1Rule = rule;
   break;
  }
 }
 h1Rule.style.margin = '10px'
 console.log (h1Rule.style.margin)
}); 
. mystyle {
  margin: 0;
} 
& lt; script src = "https://ajax.googleapis.com/ajax/libs /jquery/2.1.1/jquery.min.js"></script>
& lt; h1 class = "mystyle" & gt; Header & lt; / h1 & gt; 

Answer 2, authority 100%

Plain JavaScript

document.getElementsByClassName ('mystyle') [0] .style.margin = "50px";

or so

document.getElementsByClassName ('mystyle') [0] .style = "margin: 50px";

jQuery

$ ('. mystyle'). css ('margin', '50px');

Answer 3

Unable to rewrite CSS styling with JS. Better create a new class with the desired properties and add it.

.mystyle, .mystyle ul {
  margin: 0;
 }
 .mystyle.active {
  margin: 20px 0;
 }
 .mystyle.active ul {
  margin: 0 50px;
 }

JavaScript

document.querySelector ('. mystyle'). classList.add ('active');

jQuery

$ ('. mystyle'). addClass ('active');

Answer 4

function getClassByName (className) {
 for (var ssNum in document.styleSheets)
  for (var ruleNum in document.styleSheets [ssNum] .cssRules)
   if (document.styleSheets [ssNum] .cssRules [ruleNum] .selectorText)
    if (document.styleSheets [ssNum] .cssRules [ruleNum] .selectorText.indexOf (className) == 0)
     return document.styleSheets [ssNum] .cssRules [ruleNum];
} 
. mystyle,
.mystyle ul {
 margin: 0;
} 
& lt; button onclick = "getClassByName ('. mystyle'). style.margin = ' 30px '; "& gt; Modify class property & lt; / button & gt;
& lt; div class = "mystyle" & gt;
 & lt; ul & gt;
  & lt; li & gt; Example & lt; / li & gt;
 & lt; / ul & gt;
& lt; / div & gt; 

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions