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

Viewing the photo container before uploading while having text overlap

I'm encountering an issue where the image previews are overlapping with the text in another div. Here are the screenshots: the first one shows how it looks before the preview, and the second one shows what happens when images are added: https://i.sst ...

What could be causing the malfunction in one of the functions within my JavaScript code?

As a JavaScript beginner, I am currently working on creating a To-do App with JavaScript. Most of the functions are functioning perfectly except for one called doneTask at line 36. Despite numerous attempts to identify the issue, I have been unsuccessful s ...

Troubleshooting problems with AngularJS loading data through ajax

One of the custom widgets in my application relies on Angular functionality. On a particular page, this widget is loaded via ajax. The following content is fetched through ajax and inserted into the DOM: _abc.html: <script type="text/javascript">c ...

Initiating Firebase Configuration

Currently, I have integrated Firebase as the back-end for my app. Here is how my firebase configuration looks: const firebaseConfig = { apiKey: 'xx', authDomain: "xx", databaseURL: "xx", ...

Generate an image on Canvas using a URL link

I have a unique URL that generates canvas images with specific parameters. It functions properly when loaded in a browser. The final line of code is: window.location = canvas.toDataURL("image/png"); However, when attempting to use this URL from another ...

Is it necessary for Webpack to package all dependent node modules with the final bundle in production mode?

It's common knowledge that when we run npm run build, React scripts utilize Webpack to create a bundle by examining the entire dependency graph (following imports) and generating a bundle.js which is then stored in the dist/build folder for production ...

Does 1 CSS point amount to the same as 75% of a CSS Pixel?

Can anyone help clarify the relationship between CSS pixels and CSS points in modern web design? I've come across information stating that one CSS point is equivalent to 3/4 of a pixel. Is this accurate? Also, is it true that we can disregard the old ...

Activate a CSS button upon clicking and update the content within the div

In order to achieve the desired result of having menu CSS buttons change the content of a div when clicked, I have managed to do that successfully. However, a problem arises when clicking on the 2nd or 3rd button/link - it changes the div content, but as s ...

Divs that are 30% of their parent's width will not align vertically and will not fit in a parent div that is 100% width

I am attempting to vertically center the three child-divs <div class="section"> as 3 rows in one column within <div class="container_page_2">. When I refer to vertical alignment, I mean having an equal distance between the top of the page and ...

Move the container all the way to the left

On my page, I have a grey section with the heading 'Start Analysis' that needs to be shifted to the left along with all its contents. How can this be achieved? The HTML code for the section is as follows: <!DOCTYPE html> <html lang="en ...

Tips for transferring parameters between AJAX requests

Struggling to pass parameters between two different ajax calls, I've noticed that the params only exist within the ajax scope and not outside of it. Is there another way to achieve this without calling from one ajax success section to another ajax? He ...

What steps can be taken to update the cart if all products have been removed?

How can I implement a refresh for my cart page every time the product length is 0 without causing unreachable code? It seems like there must be a simple solution to this problem. switch (action.type){ case "REMOVE_PRODUCT": return ...

Issue with Vue.js: Child component emitting event but parent component method not triggering

When a child component makes an input change, it emits an event with some data: Vue.component('gum-option', { inheritAttrs: false, props: ['label'], template: ` <label class="gum-option"> ...

Error encountered while parsing Node.js code for MySQL query execution

I am encountering an error message from Node that reads: Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'TIMESTAMPDIFF(second, entered_at, c ...

Transferring data using a JavaScript enhanced form

I'm currently working on a search page that showcases results in a table format. I am looking to enhance the functionality using Javascript. The table is contained within a form, and each row offers multiple actions, such as adding a comment. While I ...

Angular: display many components with a click event

I'm trying to avoid rendering a new component or navigating to a different route, that's not what I want to do. Using a single variable with *ngIf to control component rendering isn't feasible because I can't predict how many variables ...

The dropdown menu is being filled with 'undefined' values when using AJAX as the data source in Typeahead

I've been trying to implement typeahead functionality, but I can't seem to find a solution on Stack Overflow that works for me. I am using an ajax source to retrieve JSON data for my products, however the typeahead feature is returning all matche ...

I'm having trouble getting $.getJSON to function properly

Has anyone encountered issues with the getJSON function in jQuery? function loadJSON(){ console.log("loading JSON") var jsonFile = themeURL+"/map.json" $.getJSON(jsonFile, function(data){ console.log("loaded JSON") $("#infobox").fadeOut(1000 ...

Ways to ensure the title changer works seamlessly for everyone

Having a title changer for elements visible in the viewport is crucial. However, the current setup only works for a single division and fails to function with multiple divisions. Click Here for Live Testing and Viewing Check out the jsFiddle for Code V ...

Firefox changes the sequence of form input attributes

Is anyone familiar with this issue and how to prevent it? I am using AJAX to populate a div with a form from a PHP file. The input element is generated in PHP as shown below: echo ('<input type="text" name="court_type_name" id="court_type_name_in ...