如何在JavaScript中为元素添加类名?

news/2024/7/19 16:34:27 标签: css, javascript, html, js, jquery
htmledit_views">

Adding class names using JavaScript can be often used to give certain functionalities to your web application. In this article, we will learn how to add class names to elements on the DOM through JavaScript?

使用JavaScript添加类名称通常可用于为您的Web应用程序提供某些功能。 在本文中,我们将学习如何通过JavaScript将类名称添加到DOM上的元素?

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/html" title=css>css/materialize.min.html" title=css>css">

    <!-- Compiled and minified JavaScript -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</head>
<style>
    body {
        background: yellow;
    }
    
    .title {
        color: white;
    }
</style>

<body>
    <div class="container">
        <h2>Blog Page </h2>
        <div class="blog">
            <h2 class="center title">How to learn JavaScript</h2>
            <div class="card">
                <p class="card-content">Lorem ipsum, dolor sit amet consectetur adipisicing elit. Libero, ut provident odit corporis quidem neque in facilis enim! Non possimus provident vitae culpa sed facere voluptatum expedita! Mollitia, rerum porro. Lorem ipsum, dolor sit amet consectetur adipisicing elit. Libero, ut provident odit corporis quidem neque in facilis enim! Non possimus provident vitae culpa sed facere voluptatum expedita! Mollitia, rerum porro. Lorem ipsum, dolor sit amet consectetur adipisicing elit. Libero, ut provident odit corporis quidem neque in facilis enim! Non possimus provident vitae culpa sed facere voluptatum expedita! Mollitia, rerum porro. Lorem ipsum, dolor sit amet consectetur adipisicing elit. Libero, ut provident odit corporis quidem neque in facilis enim! Non possimus provident vitae culpa sed facere voluptatum expedita! Mollitia, rerum porro. Lorem ipsum, dolor sit amet consectetur adipisicing elit. Libero, ut provident odit corporis quidem neque in facilis enim! Non possimus provident vitae culpa sed facere voluptatum expedita! Mollitia, rerum porro. Lorem ipsum, dolor sit amet consectetur adipisicing elit. Libero, ut provident odit corporis quidem neque in facilis enim! Non possimus provident vitae culpa sed facere voluptatum expedita! Mollitia, rerum porro.
                </p>
            </div>
            <button class="left btn">Subscribe</button>
            <button class="right btn">Mark as favorite</button>
        </div>
    </div>
    </div>

</body>
<script>
</script>

</html>

Output

输出量

html" title=javascript>javascript-1.jpg" alt="adding a class to an element in JavaScript | Example 1" style="outline: none;" />

To demonstrate, let's add some materialize classes to some of our elements. I want the title to align in the center and the blog heading to have a black background. Also, I want both our buttons to be black.

为了演示,让我们向一些元素添加一些实现类。 我希望标题在中心对齐,并且博客标题具有黑色背景。 另外,我希望两个按钮都为黑色。

<script>
	const title=document.querySelector('h2');
	const heading=document.querySelector('.title');
	const subBtn=document.querySelector('.sub');
	const favBtn=document.querySelector('.fav');

	title.classList.add('center');
	heading.classList.add('black');
	subBtn.classList.add('black');
	favBtn.classList.add('black');
</script>

Output

输出量

adding a class to an element in JavaScript | Example 2

Great! Our HTML looks much better now. We can add any CSS class to an element using JavaScript by getting a reference to that element, then using the classList property and calling then add method and pass the desired class name as a string inside. Let's say that you want to subscribe to this blog post. We'll add a class which disables the HTML and add this class when we hit the subscribe button.

大! 我们HTML现在看起来好多了。 我们可以使用JavaScript通过向元素添加任何CSS类,方法是获取对该元素的引用,然后使用classList属性并调用然后添加方法,然后将所需的类名称作为字符串传递给内部。 假设您要订阅此博客文章。 我们将添加一个禁用HTML的类,并在单击“订阅”按钮时添加此类。

.subscribed{
    display: none;
}

Inside our script tag

在我们的脚本标签内

subBtn.addEventListener('click',()=>{
    alert("You've now subscribed to this blog post!");
    subBtn.classList.add('subscribed');
})

Now when we click the subscribe button we get an alert and after that the button vanishes!

现在,当我们单击“订阅”按钮时,我们将收到警报,然后该按钮消失!

Output

输出量

adding a class to an element in JavaScript | Example 3

Cool! Let's hook up something to the favorite button as well. When you click it, I want to change its color to pink and give it a border. Can you think of how we'll do this?

凉! 让我们也将一些东西链接到“收藏夹”按钮上。 当您单击它时,我想将其颜色更改为粉红色并为其添加边框。 您能想到我们将如何做吗?

CSS:

CSS:

.fav-triggered {
    border: 2px solid pink;
    color: salmon;
}

JavaScript:

JavaScript:

favBtn.addEventListener('click',()=>{
	favBtn.classList.add('fav-triggered');
})

Output

输出量

adding a class to an element in JavaScript | Example 4

The button is styled differently on clicking!

单击时按钮的样式不同!

Thus loads of functionality can be implemented using add method to give our elements classes using JavaScript.

因此,可以使用add方法来实现功能负载,以使用JavaScript为元素类提供功能。

翻译自: https://www.includehelp.com/code-snippets/how-to-add-a-class-name-to-an-element-in-html" title=javascript>javascript.aspx


http://www.niftyadmin.cn/n/1255985.html

相关文章

Gauss–Jacobi_quadrature(MATLAB)

function [t,w] = GaussJacobi(n,beta,alpha) % [x,w] = GaussJacobi(n,alpha,beta) % find Gauss-Jacobi nodes x(1)<

stl向量_在C ++ STL中以整数向量推送和打印元素

stl向量In this example, we are declaring an integer vector, pushing the elements using a for loop with the counter starting value from 1 to 5 and then printing the value separated by space. 在此示例中&#xff0c;我们声明一个整数向量 &#xff0c;使用for循环…

[Reading] Asking while Reading

Asking while Reading ——读Java垃圾收集器与内存分配策略 Java与C之间有一堵由内存动态分配和垃圾收集技术所围成的“高墙”&#xff0c;墙外面的人想进去&#xff0c;墙里面的人却想出来。 为什么要了解垃圾回收&#xff1f; 当需要排查各种内存溢出、内存泄漏问题的时候&am…

mcq 队列_MCQ | 软件维护| 免费和开源软件

mcq 队列Q1. Which of the following is a type of Software Maintenance in SDLC? Q1。 以下哪项是SDLC中的软件维护类型&#xff1f; Corrective Maintenance 修复性维修 Adaptive Maintenance 适应性维护 Perfective Maintenance 完善的维护 All of the above 上述所有的 …

python 示例_Python日历类| 带示例的itermonthdays()方法

python 示例Python Calendar.itermonthdays()方法 (Python Calendar.itermonthdays() Method) Calendar.itermonthdays() method is an inbuilt method of the Calendar class of calendar module in Python. It uses an instance of this class and returns an iterator for t…

合页损失,铰链损失_单点铰链损失功能 使用Python的线性代数

合页损失,铰链损失Hinge Loss is a loss function used in Machine Learning for training classifiers. The hinge loss is a maximum margin classification loss function and a major part of the SVM algorithm. 铰链损失是机器学习中用于训练分类器的损失函数。 铰链损失…

PDE+图像处理-一些文献标签

1、Antil, H., & Bartels, S. (2017). Spectral Approximation of Fractional PDEs in Image Processing and Phase Field Modeling. Computational Methods in Applied Mathematics, 17(4). doi:10.1515/cmam-2017-0039 2、https://sites.oxy.edu/ron/math/300/16/comps/…

python---django中文件上传

服务端&#xff1a; def upload(req):if req.method "GET":return render(req, upload.html)else:print(req.POST.get("user"))img req.FILES.get(img)print(type(img))#(<class django.core.files.uploadedfile.InMemoryUploadedFile>, 获取的是一…