In this tutorial, we will see how to check if an element contains a specific CSS class by entering the class name.
<script setup>
import { ref } from 'vue'
const someElement = ref(null)
const checkClassName = ref(null)
const containsClass = ref(false)
const checkContainsClass = () => {
containsClass.value = someElement.value.classList.contains(
checkClassName.value
)
}
</script>
<template>
<div>
<div ref="someElement" class="color-blue">Some element</div>
<span> Contains class: {{ containsClass ? 'Yes' : 'No' }} </span>
</div>
<div>
<input type="text" v-model="checkClassName" @keyup="checkContainsClass" />
</div>
</template>
<style>
.color-blue {
background-color: aliceblue;
color: blue;
padding: 24px;
margin: 8px 0;
border: 1px solid blue;
}
</style>
Code language: HTML, XML (xml)
In the above example, the someElement variable is a reference to the div element in the template with a class of “color-blue”. The checkClassName variable is a string that holds the name of the class to check, while containsClass is a boolean variable that stores the result of the check.
The checkContainsClass function checks whether someElement contains the class specified in checkClassName. If it does, containsClass is updated to true, otherwise, it’s updated to false.
In the template section, someElement is assigned as a reference to the div element with a class of “color-blue”. The containsClass variable is used to display the result of the check as text. If containsClass is true, “Yes” is displayed, otherwise, “No” is displayed.
An input element is also included in the template, allowing the user to input a class name to check. The v-model directive is used to bind the input value to checkClassName, and the @keyup directive is used to call the checkContainsClass function whenever the user types in the input field.
In the end, a simple style rule is defined to give the color-blue class a blue background, blue text color, padding, and border.
The example code demonstrates how to create a Vue.js application that allows the user to check if an element contains a specific CSS class by typing the class name in an input field.
Here’s how the code looks in action: