using javascript to target a specific css selector attribute

I have a CSS file with the following code:

.datagrid table tbody td { color: #00496B; border-left: 1px solid
    #E1EEF4; font-size: 16px ;font-weight: normal; }

Is there a way to use JavaScript to dynamically change the font size? The code below worked for all td elements, but how can I target a specific td under the .datagrid class? Any assistance would be greatly appreciated.

css('td', 'font-size', '9px');
function css(selector, property, value) {
      for (var i=0; i<document.styleSheets.length;i++) {//Loop through all styles
          //Try add rule
          try { document.styleSheets[i].insertRule(selector+ ' {'+property+':'+value+'}', document.styleSheets[i].cssRules.length);
          } catch(err) {try { document.styleSheets[i].addRule(selector, property+':'+value);} catch(err) {}}//IE
      }
}

Answer №1

A simple way to apply css rules is by utilizing querySelectorAll method:

document.querySelectorAll(".data-grid table tbody td")

This functionality is compatible with all up-to-date web browsers.

In case you want to target a singular element:

document.querySelector(".data-grid table tbody td")

To adjust the font size of this specific element:

document.querySelector(".data-grid table tbody td").style.fontSize="12px";

Answer №2

If you want to avoid navigating through the CSS, one option is to utilize document.getElementById to target an element with a unique ID. If there is no unique ID, you can use getElementByTagName like this:

document.getElementsByTagName('div')[0] //selects the first div in the document
document.getElementsByTagName('div')[1] //selects the second div... and so on...

After selecting the element, you can modify its inline css for example:

<div id="mydiv" style="width: 200px;">

document.getElementById('mydiv').style.width = "200px"

If you prefer not to add inline styles, you have the option to access external CSS using document.styleSheets[index]. If there are multiple stylesheets, you would specify the index accordingly (e.g., document.styleSheets[0]). The rules reside in a separate array known as cssRules[index], where you can select specific rules from external CSS files such as

document.styleSheets[0].cssRules[0]
.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The CSS border on a div has inexplicably ceased functioning in Chrome, yet continues to work perfectly in

Just a moment ago, something strange happened while I was working on my memory game. After reopening the page, the borders around the divs stopped showing up when navigating with the keyboard arrows. (Click in the window to activate the arrow keys.) Normal ...

Issue with React sending a Get request to a Node server using Express

Here is a snippet of code from my React app where I am trying to retrieve data from my database based on a value that is passed. Let's start by examining the section of code that may be causing an issue: Within one of my forms, there is a function th ...

Using JavaScript and AJAX to manage and control a shell interface

Looking to create an HTML page that includes a YouTube video and utilizes JavaScript with the YouTube API. The objective is to embed a video and test if it has been fully downloaded using the YouTube API. I have set up an Apache server with MySQL and PHP ...

Ensure that the <aside> elements span the entire width of their containing parent element

I am currently designing a website and I am aiming for a specific layout. Any advice on how to achieve this would be greatly appreciated. The header of the page consists of: a logo aligned to the left within an <a> tag 2 widgets placed in <asid ...

The Jquery .remove() function will only take effect after the second click

I am currently working on implementing a notifications feature using bootstrap popover. The issue I am facing is that after a user clicks on a notification, it should be removed. However, for some reason, it requires two clicks to actually remove the notif ...

Saving form blueprints and operations in a Data Repository

My team and I are working on a sophisticated web application with a complex back end. We have hundreds of form schemas paired with their corresponding return functions, which are triggered upon form submission. These JSON objects dynamically generate forms ...

The implementation of subnavbars within a navigation bar using HTML and CSS

I am looking to align the Login button with the settings icon on the same line above the links in my navbar. Is there a way to accomplish this? Check out this fiddle that demonstrates my issue: FIDDLE Here is the code I have written: <body> < ...

Proper techniques for storing element count in Protractor

I am a beginner when it comes to using Protractor and I am not entirely satisfied with the code snippet below, even though it is functional. My goal is to store the count in a variable (named "nb_before") and use it later on. However, due to the promi ...

Embed Socket.IO into the head tag of the HTML document

After working with socket.IO and starting off with a chat example, my chat service has become quite complex. The foundation of my code is from the original tutorial where they included <script src="/socket.io/socket.io.js"></script> <scrip ...

Personalized labels for your JQuery Mobile sliders

Struggling to make this work correctly, I aim to introduce tick marks and custom labels into jQuery Mobile's slider widget. My goal is to add tick markers at 0, 25, 50, 75, and 100 with a unique string above each tick. Additionally, I want these label ...

Using a custom module in node.js to retrieve data from a mysql database

How can I retrieve select query results? I am currently getting empty or null responses. Despite attempting callback logic and using the callback function as suggested in some articles, I have yet to have any success. All of the code for my Custom Module ...

Exploring the World of Node.js Event Handling in JavaScript

After reviewing the provided code snippet: binaryServer = BinaryServer({port: 9001}); binaryServer.on('connection', function(client) { console.log("new connection"); client.on('stream', function(stream, meta) { console.log(& ...

POST data not being sent via AJAX

I am trying to use AJAX to submit form data to a PHP function, but it seems like the data is not being transmitted. Here is the code for the HTML Form: <form onSubmit="return registration();" id="registration_form"> <input type="email" id="e ...

Utilize custom scrollbar design exclusively for Windows operating system

My goal is to customize the scrollbar style of a div specifically for Windows systems. While most mobile devices have invisible scrollbars that I want to keep hidden, the aesthetics of Mac OS scrollbars are acceptable to me. What I really need is to make t ...

Troubleshooting an issue with an AJAX request

Having trouble getting the HTML back from an AJAX call - works in FF but returns "null" in IE when using alert(result.html()); Here's the code, any suggestions? Thanks! The errors variable is also null in IE. It doesn't matter what element I u ...

I'm new to Angular and I'm wondering how to close the panel by clicking on the 'x' button and also by clicking on the screen. Can anyone help me with this

Below is the HTML code I use for my button: <button class="btn btn-outlined " ng-click="vm.showCommentBox1()">Notify All</button> <div class="comment-box custom saveAll" ng-if=""><div class="panel panel-default"> ...

The final marker is consistently used by the click event

Currently exploring the Google Maps API for the first time and facing a challenge in Rails when trying to add a click event for each marker. I am looping through the team_locations model to extract latitude and longitude data in order to set up markers. ...

Storing JSON data retrieved from a fetch API request in a JavaScript global variable - a beginner's guide

I have been experimenting with the fetch API and successfully managed to log the fetched data to the console using the then() method. However, I am struggling to store this data in a global variable for later use in vanilla javascript due to the nature of ...

Troubleshooting: Angular.js error when Typescript class constructor returns undefined

I'm currently trying to create a simple TypeScript class, however I keep encountering an error stating this is undefined in the constructor. Class: class MyNewClass { items: string; constructor(){ this.items = 'items'; ...

Modify a unique custom binding handler in such a way that it is designated using an Immediately Invoked Function Expression

I am currently working on improving a custom binding handler by converting it into an Immediately Invoked Function Expression (IIFE). Despite researching IIFE online, I am still unsure of how to make the necessary changes to my custom handler. Can someon ...