简体   繁体   English

如何在HTML标签上添加类

[英]How to add a class on an HTML tag

I am trying to apply a class on HTML tag, if the tag exists. 我正在尝试在HTML标签上应用一个class ,如果该标签存在的话。

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. 我想要的是:如果HTML正文包含textarea标记,则.black类将自动应用它。

Try moving <script src="jquery.js"></script> before <script></script> containing call to $(window).load() for jQuery() to be defined when called 尝试移动<script src="jquery.js"></script><script></script>含调用$(window).load()jQuery()被定义时调用

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

If you want to apply style to HTML tags create style with Tag names Link here 如果要将样式应用于HTML标记,请创建带有标记名称的样式链接此处

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 这是我从您的源创建的一个JSFiddle

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

You don't need $(window).load(function () {}); 您不需要$(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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM