Adding a Class to Elements Based on Custom data Attributes with jQuery
Автор: vlogize
Загружено: 2025-09-18
Просмотров: 0
Описание:
Learn how to dynamically add a class to list items in jQuery based on custom `data` attributes. This guide will show you how to compare strings and implement simple scripts!
---
This video is based on the question https://stackoverflow.com/q/62378615/ asked by the user 'fred' ( https://stackoverflow.com/u/1324925/ ) and on the answer https://stackoverflow.com/a/62378660/ provided by the user 'matthias_h' ( https://stackoverflow.com/u/3943125/ ) at 'Stack Overflow' website. Thanks to these great users and Stackexchange community for their contributions.
Visit these links for original content and any more details, such as alternate solutions, latest updates/developments on topic, comments, revision history etc. For example, the original title of the Question was: compare sting and data attribute add class if it matches
Also, Content (except music) licensed under CC BY-SA https://meta.stackexchange.com/help/l...
The original Question post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license, and the original Answer post is licensed under the 'CC BY-SA 4.0' ( https://creativecommons.org/licenses/... ) license.
If anything seems off to you, please feel free to write me at vlogize [AT] gmail [DOT] com.
---
Adding a Class to Elements Based on Custom data Attributes with jQuery
Introduction
Have you ever faced a situation where you need to style specific elements on a webpage, but only if they match certain criteria? For web developers using jQuery, this can be a common requirement. Today, we will explore how to dynamically add a class to elements based on the match between a string and the value of a custom data attribute.
The Problem Statement
In our example, we have a list of items represented by <li> elements, each carrying a data-attr attribute. For instance:
[[See Video to Reveal this Text or Code Snippet]]
We want to add a new class (let's say "new") to the list item where the text matches the value of the data-attr. In this case, we would want to add the class only to item-3.
The Solution
Here, we will break down the solution into steps. We will cover a basic implementation and then build upon it to handle more complex scenarios.
Basic Implementation
To achieve our goal, we can use the following jQuery script:
[[See Video to Reveal this Text or Code Snippet]]
Explanation of the Code
$("li").each(function() {...}): We iterate over each list item (<li> elements) using the .each() function.
$(this).attr("data-attr"): This retrieves the value of the data-attr attribute of the current list item.
$(this).text(): This gets the text content of the list item.
if (...) { ... }: We check if the value of the data-attr matches the text content of the list item.
$(this).addClass("new"): If the condition is true, we add the "new" class to that list item.
CSS for Styling
To visually see the changes, you can add some CSS:
[[See Video to Reveal this Text or Code Snippet]]
Handling Multiple Values in data-attr
In some cases, the data-attr attribute may contain multiple values, and we need to check if any of them match the text. Here’s an updated implementation:
[[See Video to Reveal this Text or Code Snippet]]
Steps in the Enhanced Code
let values = attr.split(" ");: We split the data-attr string into an array of values.
for (var i = 0; i < values.length; i+ + ) { ... }: This loop checks each value against the text of the list item.
If any of the values matches, we again add the "new" class.
Example with Multiple Values
Here's how the HTML structure would look when using multiple values for the data-attr:
[[See Video to Reveal this Text or Code Snippet]]
Conclusion
Using jQuery to compare strings and manage class additions dynamically based on custom data attributes simplifies web development significantly. Whether you are dealing with single or multiple values, the above methods provide a streamlined approach to achieving your desired functionality.
Feel free to incorporate these snippets into your projects, tweaking as necessary for your unique use cases. Happy coding!
Повторяем попытку...
Доступные форматы для скачивания:
Скачать видео
-
Информация по загрузке: