Tips for including a new class in an HTML element

My goal is to add a specific class to an HTML tag, if that tag exists.

This is the code I have attempted:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>index</title>

    <style>
        .black
        {
            background:#000;
            color:white;
        }

    </style>
    <script type="text/javascript">
        $(window).load(function () {
            $('textarea').addClass('black');
        });
    </script>
</head>
<body>

    <div>


        <textarea>content</textarea>


    </div>

    <script src="jquery.js"></script>

</body>
</html>

Desired Outcome: When the HTML body contains a textarea tag, I want the .black class to be automatically applied to it.

Answer №1

To ensure that jQuery() is defined when called, try moving the

<script src="jquery.js"></script>
above the <script></script> containing the call to $(window).load()

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>index</title>
  <style>
    .black {
      background: #000;
      color: white;
    }
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
  <script type="text/javascript"gt;
    $(window).load(function() {
      $('textarea').addClass('black');
    });
  </script>
</head>

<body>
  <div>
    <textarea>content</textarea>
  </div>
</body>

</html>

Answer №2

If you're looking to add some flair to your HTML elements, consider creating a style using tag names. Check out this helpful link for more information.

For example:

textarea
{
   background:yellow;
   color:red;         
}

This CSS will apply the specified styles to all textarea tags on your webpage. Feel free to view the JSFiddle I've set up using your code snippet:

https://jsfiddle.net/sumeetkumar001/sxxkjbh2/

Answer №3

You can skip using $(window).load(function () {});, just keep this line:

$('textarea').addClass('black');

Check out the demo here!

$('textarea').addClass('black');
.black {
   background:#000;
   color:white;
}
<div>
    <textarea>content</textarea>
</div>

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

Is it possible for a media query to target only 2 elements instead of all 3?

Currently, I am dealing with an older website for a client, and it appears that a media query is not correctly affecting three specific classes out of the total. These problematic classes are .free-ship, .wholesale, .chronicles The CSS styling for these c ...

Ways to change columns into rows with CSS

Hey there! I'm looking for a way to convert columns into rows and vice versa. In my table, I have both column headers and row headers on the left side. The row headers are simply bold text placed next to each row to describe its content. I want to op ...

The error detected in the W3Schools validator pertains to CSS for audio elements that do not contain

Could somebody kindly explain why this code is being flagged as an error on w3schools? audio:not([controls]) { display: none; height: 0; } ...

Creating a function that uses setInterval to continuously update the input with a specific value

I am looking to use the setInterval function to continuously update the value of #test1. Additionally, I want the value of #test1 to be cleared and reset to 1 second after the user clicks a button. Example output can be found here: http://jsfiddle.net/eK ...

Unable to retrieve property from NextRequest

Currently, I am attempting to utilize MiddleWare in conjunction with Next.js's Middleware and JWT. Upon logging cookies and the typeof cookies variable, this is what I see on my console: { token: 'token='myToken'; Path=/' } obj ...

Troubles arise when hovering over the <strong> tag and the <h4> element

While hovering over my h4 tag in the table, everything functions correctly. However, when I hover over the strong tag inside the h4 element, the strong tag inherits the same hover effect as the h4 tag. The structure of each td element within the table is ...

Retrieve information from the script tag

Is there a method to extract data from a <script> tag, specifically targeting the 30-minute table on AEMO's website (AEMO Website)? In order to access the data table, I attempted to scrape it but encountered an issue where the button and table ...

Unable to utilize jQuery library in AngularJS partial HTML files, despite being loaded in the index.html file

I have been working with a web template that utilizes jQuery image gallery and other elements. Now, I am looking to convert this template into an AngularJS structure. To do so, I have created partial HTML pages like slider.html or contact.html along with t ...

Two interactive dropdown menus featuring custom data attributes, each influencing the options available in the other

Looking to create interactive select boxes based on the data attribute values? This is the code I currently have: HTML <select id="hours" onchange="giveSelection()"> <option value="somethingA" data-option="1">optionA</option> <o ...

Can date ranges be utilized as separate date items on the time scale in D3.js?

I have a chart that resembles the one shown below, however, there is a crucial component missing. Currently, my time scale follows the standard format as depicted in the first picture. I am looking to convert it to the time scale seen in the second picture ...

What is the best way to delete a container when its child element includes a specific string?

I run a website that compiles video clips from various sources, including YouTube. Occasionally, some clips appear as private videos. I am looking to use jQuery to apply the display:none; property to the entire div when the class a.colorbox.cboxElement con ...

Arrays passed as query parameters to Next.js router.query may result in the value being

When trying to pass objects from an array to another page using router.query, individual objects like router.query.title work as expected. However, when attempting to pass arrays such as router.query.reviews, it returns something like reviews: ['&apos ...

Creating a rotating circle in CSS with ion-slides: A step-by-step guide

Hello, I am attempting to develop a circular object that will rotate in the direction it is dragged. Within this circle, there are elements positioned along the border so that these elements also spin accordingly. To illustrate, below are the specific elem ...

Maximizing the potential of typescript generics in Reactjs functional components

I have a component within my react project that looks like this: import "./styles.css"; type InputType = "input" | "textarea"; interface ContainerProps { name: string; placeholder: string; as: InputType; } const Conta ...

Record the success or failure of a Protractor test case to generate customized reports

Recently, I implemented Protractor testing for our Angular apps at the company and I've been searching for a straightforward method to record the pass/fail status of each scenario in the spec classes. Is there a simple solution for this? Despite my at ...

Utilizing Ajax to fetch a div element from a web page

Hey there! I have a link set up that loads a page into a specific div ID, which is #ey_4col3. The issue I'm facing is that it loads the entire page along with all its contents, but what I really want to load from that page is just the content within ...

Distinguishing between client side rendering and server side rendering is the backbone of web development

My goal is to give users the option to request webpages from my website either directly from the server or by clicking on links, which will be managed by Backbone's router. When a user requests a webpage directly from the server, they will receive a ...

What is the best way to customize the link style for individual data links within a Highcharts network graph?

I am currently working on creating a Network Graph that visualizes relationships between devices and individuals in an Internet of Things environment. The data for the graph is extracted from a database, including information about the sender and receiver ...

Guide to tallying the occurrences of a specific key within an object array and attaching the count to each key's current value

Is there a way to determine the number of occurrences of the 'value' key within an object that is part of an array, and then add the count to each value if applicable? In this case, 'a' represents the original data var a = [ { id: ...

Connect individuals based on specific criteria within a nested array

My MongoDB collection looks something like this: _id: ObjectId("5cb089e459552d8b8cc6a9e4") username: "admin" password: "12345" gender: "male" interestedIn: "female" movie: Array 0: Object id: "Avatar" title: "Avatar" poster: "~" 1: Object ...