What is preventing the assignment of a class attribute inline using JavaScript?

<html>
  <head>
    <style>     
      .tagging {
        border: 1px solid black;
        width: 20px;
        height: 30px;
      }
    </style>
    <script>
      window.onload = function() {
        var div = document.getElementsByTagName("div");
        div[0].class = "tagging";
      }     
    </script>
  </head>
  <body>
    <div></div>
  </body>
</html>

This is the code I wrote. I am curious why it does not seem to work when assigning the class attribute through JavaScript, but works fine when done inline in HTML

<div class="tagging"></div>

Answer №1

You should utilize the className property.

Give this a shot:

div[0].className = "tagging";

If you wish to append the class to the existing one, use:

div[0].className += " tagging"; // ensure to add white-space

See a demonstration here

Reference: Check out MDN's explanation on className.

Answer №2

Try using className instead:

var div = document.getElementsByTagName("div");
div[0].class = "tagging";

Change it to:

var div = document.getElementsByTagName("div");
div[0].className = "tagging";

See a demonstration here: jsFiddle

Answer №3

<div id="uniqueDiv" class="specificClass">
    <img ... id="uniqueImage" name="customImage" />
</div>

Next:

var element = document.getElementById("uniqueDiv");
element.className = element.className + " additionalClass";

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

What steps do I need to take to include React in my background.js script for a chrome

I'm currently facing an issue with my React code that I need to include in my background.js file. However, I encountered the following error message: SyntaxError: Cannot use import statement outside a module The specific import causing this error is: ...

Unexplained quirks observed in AngularJS $watch during the initialization of a controller

I am working with a code snippet that utilizes AngularJS: var app = angular.module('Demo', []); app.controller('DemoCtrl', function ($scope) { function notify(newValue, oldValue) { console.log('%s => %s', oldValue, ...

Issues with Angular preventing app from launching successfully

So I've been working on a Cordova app with AngularJS and everything seems to be running smoothly in Chrome and other browsers. However, when I try to install the apk on Android, AngularJS doesn't seem to execute the index.html upon launch. What& ...

Set the rowspan to 2 when the v-for index does not equal 2

This is the table I am working with: <table class="table table-condensed table-sm table-striped table-bordered" id="list"> <thead> <tr> <th v-for="(column, index) in columns" :key=& ...

Tips on creating a bot that patiently waits for responses before asking follow-up questions

I'm trying to develop my own bot for economics, but I've hit a snag. My goal is to have the bot ask a question, wait for an answer, and then ask another question, and so on. Can anyone offer some guidance on this issue? Here's the code I hav ...

Customizing the date-select widths: A step-by-step guide

I've been struggling with adjusting the width of different instances of this line: <%= f.date_select :deadline, :order => [:month, :day, :year], class: 'date-pick', id: 'goal' %> Despite creating unique ids for select, d ...

Chrome method for creating Flexbox columns of equal height

I am implementing a simple 2-column layout and I want to utilize Flexbox to ensure equal heights for the columns: HTML <div class="row flex"> <!-- menu --> <div class="col-xs-4"> <aside> Menu content wi ...

Return true in an incorrect manner

Coderbyte Challenge 7 Need help with a function that checks if every letter in the string is bounded by '+' signs. The code provided seems to be returning incorrect results - it should return false for the input string below as 'k' is ...

Alexa Skill: Successful with the initial query but fails with the subsequent one

An issue has been identified with the Alexa skill where it works for the first question but not the second one. The skill involves a jumbled letters quiz utilizing the following array: var arr = [{"Q":"dcha","A":"chad"},{"Q":"goto","A":"togo"},{"Q":"alim" ...

The video is not displaying on my website

I recently added a video to my webpage that is 3:48 minutes long. However, even though I have the navigation bar and sound in place, the video does not seem to be displaying properly. Here is an image of how it appears: https://i.stack.imgur.com/HeN41.png ...

Explore the world of HTML event listening through .NET integration

Imagine this scenario: within an HTML page, using an UpdatePanel, you have a loading animated gif spinning while ASP.NET processes data from a webservice. I'm curious if there's a way to create an Event in .NET code that can be detected on the H ...

I am experiencing difficulties with the PHP login form on MAMP as it is not loading properly, displaying only a

Having trouble with php not loading when I open my browser. Here is my database info: MySQL To manage the MySQL Database, you can use phpMyAdmin. If you need to connect to the MySQL Server from your own scripts, use these connection parameters: Host ...

What could be causing the first() rxjs operator to repeatedly return an array?

I'm currently facing an issue with a service that has the following function signature: getSummary(id: string, universe: string): Observable<INTsummary[]> My requirement is to retrieve only the first item in the INTsummary[] array when calling ...

Is it possible to develop an image that can be zoomed in and out using the mouse

$(document.createElement('img')) .width(imgW) .height(imgH) .addClass('img_full') .attr('src', $(this).attr('data-src')) .draggable() .css({ &a ...

The utilization of conditional expression necessitates the inclusion of all three expressions at the conclusion

<div *ngFor="let f of layout?.photoframes; let i = index" [attr.data-index]="i"> <input type="number" [(ngModel)]="f.x" [style.border-color]="(selectedObject===f) ? 'red'" /> </div> An error is triggered by the conditional ...

Prevent bouncing effect in Cordova/Phonegap specifically for the header and footer sections

I've utilized the property in the config.xml file to prevent bouncing in the webview (iOS): <preference name="DisallowOverscroll" value="true" /> It's working as intended. However, I'm wondering if there's a way to disable bounc ...

Using node.js to modify the appearance of the form submission button's color

When using node.js to insert data from an HTML form into a database, validation typically occurs on the server side. I am wondering if there is a way to customize the CSS class associated with the submit data button in node.js. For example, I would like ...

The cross-origin resource sharing (CORS) functionality is functioning properly on the

I've encountered an unusual problem with express cors. While my Cors configuration works perfectly on localhost, it fails to function in the production environment. Every time I encounter the same error. Failed to load : Response to preflight r ...

What are the best strategies for optimizing my CSS drop down menu to be both responsive and mobile-friendly?

I am struggling to make my current CSS and HTML menu fully responsive and mobile-friendly. I have researched solutions from other sources but have been unable to implement them successfully. I am seeking help in modifying my menu so that it adjusts to smal ...

refresh PHP automatically using JavaScript

Working on my Laravel application, there is a JavaScript function that I have defined: function abc(){ var x = '<?php ($user && ($user->first_name == "" || $user->number == "")) ?>'; } Upon initial page load, the variable ...