Is it possible to modify HTML style using JavaScript by selecting the class name without using jQuery?

I've been experimenting with some code and noticed that when I use the element ID, it works fine, but when I try to use the class name, it doesn't work...

<!DOCTYPE html>
<html>
<body>

<p id="p1" class="theClass">Hello World!</p>
<p id="p2">Hello World!</p>

<script>

document.getElementById("p2").style.color = "blue";
document.getElementsByClassName("theClass").style.color = "blue";

document.getElementById("p2").style.fontSize = "larger";
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>

Check out the screenshot of the output:

https://i.sstatic.net/P1uTE.png

Answer №1

getElementsByClassName does not return an element, but rather an HTMLCollection. If you want to apply a style to a specific element within the collection, you should first select that individual element:

document.getElementsByClassName("theClass")[0].style.color = "blue";
<p id="p1" class="theClass">Hello World!</p>

However, if you are targeting a single element, it is recommended to use querySelector for better performance:

document.querySelector('.theClass').style.color = "blue";
<p id="p1" class="theClass">Hello World!</p>

When dealing with multiple elements sharing a common class name, using getElementsBy* methods can be cumbersome. Consider utilizing querySelectorAll instead, which returns a static NodeList. Unlike HTMLCollection, NodeList allows direct iteration without any change during iteration and offers more flexibility:

document.querySelectorAll('.theClass')
  .forEach(p => p.style.color = "blue");
<p class="theClass">Hello World!</p>
<p class="theClass">Hello World!</p>
<p class="theClass">Hello World!</p>

Answer №2

Using document.getElementsByClassName
allows you to obtain a list of nodes. However, this list does not have a style property. To apply styles, you must iterate through the list.

If there is only one div present, you can do the following:

document.getElementsByClassName("theClass")[0].style.color = "red" 

PS. Remember to always check your browser's console if something is not working as intended. You may encounter an error message like cannot access ... .style of ...

document.getElementById("p2").style.color = "blue";
document.getElementsByClassName("theClass")[0].style.color = "blue";

document.getElementById("p2").style.fontSize = "larger";

var elements = document.getElementsByClassName('theClass1');

for(var i=0; i< elements.length; i++){
   elements[i].style.color = "green"

}
<!DOCTYPE html>
<html>
<body>

<p id="p1" class="theClass">Hello World!</p>
<p id="p2">Hello World!</p>

<p id="p12" class="theClass1">Hello World 1!</p>
<p id="p14" class="theClass1">Hello World 2!</p>
<p id="p13" class="theClass1">Hello World 3!</p>

<p>The paragraph above was changed by a script.</p>

</body>
</html>

Answer №3

Give this a shot:

document.querySelector(".theClass").style.color = "blue";

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

Creating a Wordpress Metabox that utilizes radio inputs generated with Javascript instead of the traditional checked() function in Javascript as an alternative

Despite my efforts to find a solution on various forums, I am still stuck with this issue without making any progress. The code snippet below contains two Radio inputs. These inputs are generated on the post edit page of Wordpress CMS and their values com ...

Is your component failing to re-render after a state change?

I am currently in the process of developing a random quote generator. The main feature is a quote box that showcases quotes along with their respective authors. I have implemented a method that triggers upon button click to randomize the list of quotes and ...

Unique option preservation on customized HTML select menus - Maintain original selection

Currently, I am attempting to replicate a custom HTML select based on the example provided by W3 Schools. You can view the demo through this link: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_custom_select The issue I am encountering is that ...

Adjust the size of the buttons based on the width of the screen

I have successfully implemented a dropdown menu with both text and an icon. However, I am now faced with the challenge of removing the text while retaining the icon when the screen width is reduced to a maximum of 768px. Is it possible to modify the conten ...

Parcel React component library throws an error stating that "require is not defined

Error message: Uncaught ReferenceError: require is not defined at index.js?5WdmUIncGTkIrWhONvlEDQ:1:1 (anonymous) @ index.js?5WdmUIncGTkIrWhONvlEDQ:1 First lines of index.js: require("./index.css"); var $cI6W1$lodash = require("lodash&q ...

Iframe Interactivity

My goal is to create an interactive iframe that will match the current parent URL (). For example, if I have an iframe pointing to http://www.google.com and click a link within the iframe, it should update the parent URL to , and then load the clicked con ...

Can a snapshot be taken of an auto-generated ID document in FireStore?

Currently, I am working on developing both a mobile app and web app for my Final Year Project. As someone relatively new to Firestore, I am using a single instance of it to store data. When a customer registers through the mobile app, their information ge ...

Transform the appearance of a complex image by altering its color using CSS

In my quest to bring a unique functionality to life, I am looking to achieve the following: I want to layer two transparent images within a <div>: one representing an object and the other depicting a glowing effect around the object. When hovering ...

The POST request is not functioning. An error has occurred: Unable to retrieve response data - no content is available for the preflight request

Having trouble making a post request from my client side to the back-end. Even with the new movie hardcoded, it keeps returning an error stating that there was a failure in loading the response data. Below is the code for the front-end: //Fetch request t ...

Assign a role to a user using the latest version of discord.js

I recently started using the latest version of discord.js in node.js and I'm facing an issue with adding a user to a role. It looks like bot.addUserToRole() has been removed from the codebase. Is there another way to achieve this if I only have acces ...

How to convert JSON data (excluding headers) into a string array using TypeScript

I am attempting to extract the raw data from the JSON without including the headers. For example, I want to retrieve '1' but not 'ID', or 'foo' but not 'Name'. [{ID = 1, Name = "foo", Email = "<a href="/cdn-cgi/l ...

Steps for generating a current date and a date one year in the past

In my WebService, I need to update the DATEFIN to today's date and the DATEDEBUT to a date that is one year prior. Currently, the setup looks like this: see image here At the moment, I am manually inputting the dates. How can I automate this proces ...

Iterate through several table data cells, extract various data points, and populate an array

I am facing a challenge with two tables on my webpage. The second table is dynamically populated with HTML using JavaScript. To accomplish this, I am checking if the <tr> tags inside the tbody are empty by using the following code: var rowCount = $( ...

Disabling pagination for custom searches in datatables

I need to implement a search filter based on only 2 columns using text fields. So, I have set up two text fields: <input type="text" id="type" name="type" placeholder="Filter by User Type"></td> <input type="text" id="dept" name="dept" pla ...

The background image of the li element is not appearing in Firefox browser

I'm facing an issue with an HTML code snippet on my page that looks like this: <section class ="sidebar"> <ul> <li class="facebook">Facebook</li> <li class="linkedin">LinkedIn& ...

Text that appears as an HTML button is displayed after being compiled using the $

I am attempting to generate a pop up dialog with two buttons using JS code in angular. The script below is what I am using to create the buttons... var html = $('<button ng-click = "cancelAlert()" > Cancel</button > <button ng-click="c ...

What steps should I take to ensure that my table is positioned above my ContentPlaceHolder?

I'm currently working on setting up a menu in the MasterPage that will appear when a hyperlink is clicked. The YardimDokumaniMenuAHREF hyperlink triggers the display of the menu. Upon clicking it, a JavaScript function is invoked. However, I am facing ...

Anonymized Score Reporting through Google Analytics analytics.js

Recently, I've been working on setting up Google Analytics for tracking my web game. Everything seems to be working fine, except for one issue - when I check my custom report the next day after testing the game, I notice that all the scores have been ...

JQuery selector is unable to locate element when passing Span Id

I've been researching and I believed this solution would be effective, but it seems that I made a mistake. The issue involves using Ajax Manager within a function. Here is my Javascript: function makeGetRequest2(wordId, docId) { var ajaxManager ...

Use vtip jQuery for showcasing titles

Currently, I am utilizing the vTip plugin for displaying titles upon hover. Here is a snippet of my code: http://jsfiddle.net/bnjSs/ In my HTML, there's a Div with the ID #showTitles. Whenever this Div is clicked, I aim to toggle the display of all ...