• 0

[Javascript] Change CSS Attribute


Question

Hi there.

I've managed to change the padding of an element using javascript. I changed:

#content {
border-right: 1px solid #e6e6e6;
margin: 0 -31px -9999px -5.1%;
padding: 106px 30px 9999px 5.1%;
background: #fff url(../images/bg-content.gif) repeat-y;
position: relative;
z-index: 2;
}

using:

document.getElementById("content").style.padding = "106px 0px 9999px 0%";

How would I go about changing a css attribute that's a class?

i.e.:


.post p {margin: 0;}

Link to comment
https://www.neowin.net/forum/topic/1134314-javascript-change-css-attribute/
Share on other sites

7 answers to this question

Recommended Posts

  • 0

Hi there.

I've managed to change the padding of an element using javascript. I changed:

#content {
border-right: 1px solid #e6e6e6;
margin: 0 -31px -9999px -5.1%;
padding: 106px 30px 9999px 5.1%;
background: #fff url(../images/bg-content.gif) repeat-y;
position: relative;
z-index: 2;
}

using:

document.getElementById("content").style.padding = "106px 0px 9999px 0%";

How would I go about changing a css attribute that's a class?

i.e.:


.post p {margin: 0;}

You could get all child elements of ".post" using the jquery children function and set the values using the css function. :) Here is an example:


//jquery example
$(".post").children().css('padding', '106px 0px 9999px 0%');
[/CODE]

  • 0

Sorry I'm not familiar with how to use jquery but I know jquery.js is included in the head of the document.

At the moment I've added this into the body of a post:


<script>
function myFunction() {
document.getElementById("content").style.padding = "106px 0px 9999px 0%";
}
</script>


<button onclick="myFunction();">click</button>

This changes the padding in the matching css #content rule.

I want to change .post p {margin: 0;} to .post p {margin-right: -50px;}

  • 0

Sorry I'm not familiar with how to use jquery but I know jquery.js is included in the head of the document.

At the moment I've added this into the body of a post:


<script>
function myFunction() {
document.getElementById("content").style.padding = "106px 0px 9999px 0%";
}
</script>


<button onclick="myFunction();">click</button>

This changes the padding in the matching css #content rule.

I want to change .post p {margin: 0;} to .post p {margin-right: -50px;}

I actually made one mistake in my example code. The children function call should look like this: ".children('p')". What you would do is modify your javascript function as shown below:


<script>
function myFunction() {
document.getElementById("content").style.padding = "106px 0px 9999px 0%";
$(".post").children('p').css('margin-right', '-50px');
}
</script>
[/CODE]

So you would basically just add the line of code that I gave you below the existing line of code in your javascript function.

  • 0

Thanks for your reply.

Unfortunately I get this error if I run the code:



Uncaught TypeError: Property '$' of object [object Window] is not a function
myFunction
onclick

this is in the head:

&lt;script type="text/javascript" src="https://website.com/wp-content/themes/yerba/js/jquery.main.js"&gt;&lt;/script&gt;

Could there be another way to do this?

If I add

&lt;style&gt;.post p {margin-right: -50px;} &lt;/style&gt;

to the bottom of the <head>

it adds the proper margin to the element.

Trouble is it occurs across the whole wordpress site. I only want it to load upon a certain page

I tried adding:

&lt;script&gt;

if (document.title == "Contact Us") {
document.write("&lt;style&gt;.post p {margin-right: -50px;} &lt;/style&gt;");
}
&lt;/script&gt;

to the end of the head section but that doesn't work. I may be using it incorrectly though. Very new to js.

  • 0

Thanks for your reply.

Unfortunately I get this error if I run the code:



Uncaught TypeError: Property '$' of object [object Window] is not a function
myFunction
onclick

this is in the head:

&lt;script type="text/javascript" src="https://website.com/wp-content/themes/yerba/js/jquery.main.js"&gt;&lt;/script&gt;

Could there be another way to do this?

If I add

&lt;style&gt;.post p {margin-right: -50px;} &lt;/style&gt;

to the bottom of the <head>

it adds the proper margin to the element.

Trouble is it occurs across the whole wordpress site. I only want it to load upon a certain page

I tried adding:

&lt;script&gt;

if (document.title == "Contact Us") {
document.write("&lt;style&gt;.post p {margin-right: -50px;} &lt;/style&gt;");
}
&lt;/script&gt;

to the end of the head section but that doesn't work. I may be using it incorrectly though. Very new to js.

No problem at all! :) Ok, it may not be properly accessing jquery in that case. Try changing this line:


<script type="text/javascript" src="https://website.com/wp-content/themes/yerba/js/jquery.main.js"></script>
[/CODE]

To this:

[CODE]
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
[/CODE]

Here is a link to describe additional issues that could cause the error message that you are seeing (just in case my solution fails for some reason): http://stackoverflow...-not-a-function

  • 0

Thanks buddy. I'm packing up for today and my heads spinning focusing on such a simple problem for so long.

I've solved it presently using php:


&lt;?php
$currentpageurl=$_SERVER['REQUEST_URI'];
if ($currentpageurl = "/contact-us/") {
echo "&lt;style&gt;#content {padding: 106px 0px 9999px 0%} .post p {margin-right: -50px;}&lt;/style&gt;";
}
?&gt;

Wish I'd thought of that first thing!

  • 0

Thanks buddy. I'm packing up for today and my heads spinning focusing on such a simple problem for so long.

I've solved it presently using php:


&lt;?php
$currentpageurl=$_SERVER['REQUEST_URI'];
if ($currentpageurl = "/contact-us/") {
echo "&lt;style&gt;#content {padding: 106px 0px 9999px 0%} .post p {margin-right: -50px;}&lt;/style&gt;";
}
?&gt;

Wish I'd thought of that first thing!

You are very welcome! :) I don't blame you at all. Working on problems like this for so long can bring headaches very easily. I know from past experience. lol. Also, just in case you want to use jquery in the future, I found another link that may help. I noticed from your code that you may be using wordpress. If so, the following link should be helpful for future use: http://www.ericmmartin.com/5-tips-for-using-jquery-with-wordpress/

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • JetBrains is working to cut false positives in RustRover 2026.2 by David Uzondu Recently, JetBrains released the fifth EAP build of its dedicated IDE, RustRover 2026.2, bringing improvements like a Run gutter icon for criterion_main! macro benchmarking and a feature that alerts you when there are unused traits in your current scope. Now, the company is out with a blog post addressing one of the "most common" complaints from users: false positives. In RustRover, a false positive occurs when the editor incorrectly highlights something as an error even though the project compiles and runs successfully. This mismatch flags a gap between the IDE's internal intelligence and the actual compiler. When the editor flashes red warnings over perfectly valid code, developers lose trust in the tool, which stalls momentum. Traditionally, RustRover runs cargo check to detect compiler errors and warnings, but it also relies on its own code analysis engine to power real-time features. To provide quick feedback, this engine parses your source code into a syntax tree while inferring types and resolving names as you type. Because this engine must work on broken, half-written code and react instantly, its logic sometimes diverges from the compiler's, producing false positives that do not exist in the compiler's eyes. JetBrains said that it has a "dedicated task force" focused specifically on identifying and fixing false positives by analyzing user reports and examining large-scale open-source projects. To speed up this process, the team built an internal system modeled after Crater, the famous Rust project that compiles and runs tests for every single crate published on crates.io. This automated pipeline compares the diagnostics from RustRover's analysis with actual compiler output to catch discrepancies before they reach users, ensuring smoother workflows. RustRover, for those who're unaware, is a dedicated IDE designed specifically for Rust developers. It's been around for a couple of years now, providing features like built-in debugging via LLDB, seamless cargo integration, advanced macro expansion, and HTML support. JetBrains distributes the app under two licensing models: a paid commercial subscription and a free option for non-commercial use.
    • Last year I bought the 2TB variant for $114 on Amazon. That's crazy that the 1TB is now 67% more expensive for half the storage, even with the newer T9 already on the market. And that's considered a good deal.
    • You can disable all non needed features from Brave. There is also Brave Origin which removes them entirely and it is free for Linux.
    • I wish I could use Brave but the tab suspension feature is horrible. It doesn't suspend them like Edge does. Even after 2h open with 70+ tabs (same as Edge), it has 2GB more consumption than Edge for no reason.
    • TeamViewer 15.78.4.0 by Razvan Serea TeamViewer is the fast, simple and friendly solution for remote access over the Internet - all applications in one single, very affordable module. Remote control of computers over the Internet, Instantly take control over a computer anywhere on the Internet, even through firewalls. No installation required, just use it fast and secure. Training, sales and teamwork, TeamViewer can also be used to present your desktop to a partner on the Internet. Show and share your software, PowerPoint presentations etc. File transfer, chat and more, Share your files, chat, switch the direction during a teamwork session, and a lot more is included in TeamViewer. TeamViewer key features: Cross-platform remote access (Windows, macOS, Linux, Android, iOS, IoT) Attended and unattended remote control Secure file transfer between devices Remote printing to local printers Multi-monitor support with easy switching Wake-on-LAN for sleeping devices Session links for quick connections (no password sharing) Web client access (no installation needed) End-to-end encryption (AES-256) Two-factor authentication and access controls AI-powered session insights and reporting Mass deployment and device management tools Customizable allow/block lists for security Command line and script execution remotely Performance monitoring and analytics dashboards TeamViewer 15.78.4.0 changelog: Improvements Permissions inheritance has been improved, increasing reliability when permissions are assigned to user group managers. Bugfixes Fixed a bug where 'Show details' button was not showing up on command bar upon selection of a device group. Fixed a bug which was causing the legacy groups to disappear when applying hide offline filter in basic view. Fixed a bug where devices were loading infinitely after login. Fixed a bug which was causing crash in application. Download: TeamViewer 15.78.4.0 | 32-bit | Portable | Mac | ~70.0 MB (Free for personal use) View: TeamViewer Home Page | Release Notes | Screenshot Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • One Year In
      Primer1st earned a badge
      One Year In
    • Experienced
      JayZJay went up a rank
      Experienced
    • Reacting Well
      Sir_Timbit earned a badge
      Reacting Well
    • Week One Done
      rubentuben8 earned a badge
      Week One Done
    • Week One Done
      ARaclen earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      524
    2. 2
      PsYcHoKiLLa
      231
    3. 3
      Edouard
      135
    4. 4
      ATLien_0
      88
    5. 5
      Steven P.
      82
  • Tell a friend

    Love Neowin? Tell a friend!