msz
msz

Reputation: 309

How to add a class on an HTML tag

I am trying to apply a class on HTML tag, if the tag exists.

I have tried this code:

<!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>

What I want: If the HTML body contains a textarea tag then the .black class will apply it automatically.

Upvotes: 0

Views: 301

Answers (3)

sumeet kumar
sumeet kumar

Reputation: 2648

If you want to apply style to HTML tags create style with Tag names Link here

For your case

textarea
{
   background:yellow;
   color:red;         
}

this shall apply to all the text area tag on the document. here is a JSFiddle i created from your source

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

Upvotes: 0

guest271314
guest271314

Reputation: 1

Try moving <script src="jquery.js"></script> before <script></script> containing call to $(window).load() for jQuery() to be defined when called

<!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">
    $(window).load(function() {
      $('textarea').addClass('black');
    });
  </script>
</head>

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

</html>

Upvotes: 5

AleshaOleg
AleshaOleg

Reputation: 2211

You don't need $(window).load(function () {});, simply leave this line:

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

Here is demo.

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

Upvotes: -2

Related Questions