Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How To Select Divs That Has A Specific HTML Content That Matches Values?
The div tag is one of the most fundamental HTML elements used to create content divisions and sections on web pages. When building dynamic web applications, you often need to select specific div elements based on their HTML content or attribute values for styling, manipulation, or interaction purposes.
This article demonstrates various methods to select div elements that contain specific HTML content or match particular values using CSS selectors, JavaScript, and HTML attributes.
Method 1 - Using JavaScript to Select Divs by Text Content
JavaScript provides powerful methods to traverse the DOM and select elements based on their content. You can loop through div elements and compare their textContent or innerHTML properties against specific values.
Example
Following example demonstrates selecting divs containing specific text content using JavaScript
<!DOCTYPE html>
<html>
<head>
<title>Select Divs by Text Content</title>
<style>
.cricketers {
width: 200px;
font-family: Arial, sans-serif;
}
.cricketers div {
padding: 8px;
margin: 4px 0;
border: 1px solid #ddd;
}
.marked {
background-color: #27AE60;
color: white;
font-weight: bold;
}
</style>
</head>
<body>
<h2>Cricket Players</h2>
<div class="cricketers">
<div>MSD</div>
<div>KOHLI</div>
<div>YUVI</div>
<div>SEHWAG</div>
<div>SACHIN</div>
</div>
<script>
const selected = ["MSD", "SACHIN"];
const containerElement = document.querySelector('.cricketers');
for (let i = 0; i < containerElement.children.length; i++) {
let playerName = containerElement.children[i].textContent.trim();
for (let player of selected) {
if (player === playerName) {
containerElement.children[i].innerHTML += ' - Selected';
containerElement.children[i].classList.add("marked");
}
}
}
</script>
</body>
</html>
The output shows the cricket players list with selected players highlighted in green
Cricket Players MSD - Selected (green background, white text) KOHLI (normal styling) YUVI (normal styling) SEHWAG (normal styling) SACHIN - Selected (green background, white text)
Method 2 - Using CSS Attribute Selectors
CSS attribute selectors allow you to select elements based on their attribute values. This method is particularly useful when you have control over the HTML markup and can add custom data attributes.
CSS Attribute Selector Syntax
/* Exact match */ [data-content="value"] /* Starts with */ [data-content^="value"] /* Contains */ [data-content*="value"] /* Ends with */ [data-content$="value"] /* Case-insensitive matching */ [data-content="value" i]
Example
Following example uses CSS attribute selectors to style table cells based on their data content
<!DOCTYPE html>
<html>
<head>
<title>CSS Attribute Selectors</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
table { border-collapse: collapse; width: 100%; }
td { padding: 10px; border: 1px solid #ddd; text-align: center; }
/* Select cells with exact match "female" */
td[data-content="female"] {
background-color: #E8DAEF;
color: #7D3C98;
font-weight: bold;
}
/* Select cells starting with "p" (case-insensitive) */
td[data-content^="p" i] {
background-color: #D5F4E6;
color: #239B56;
font-weight: bold;
}
/* Select cells containing "8" */
td[data-content*="8"] {
background-color: #FADBD8;
color: #DE3163;
font-weight: bold;
}
</style>
</head>
<body>
<h2>Employee Data with Conditional Styling</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Gender</th>
<th>Age</th>
</tr>
</thead>
<tbody>
<tr>
<td data-content="John">John</td>
<td data-content="male">Male</td>
<td data-content="28">28</td>
</tr>
<tr>
<td data-content="Priya">Priya</td>
<td data-content="female">Female</td>
<td data-content="18">18</td>
</tr>
<tr>
<td data-content="Peter">Peter</td>
<td data-content="male">Male</td>
<td data-content="35">35</td>
</tr>
</tbody>
</table>
</body>
</html>
The output displays a table with conditional styling based on data attributes
Employee Data with Conditional Styling Name | Gender | Age --------|---------|---- John | Male | 28 (age cell highlighted in pink - contains "8") Priya | Female | 18 (name cell in green - starts with "p", gender in purple - exact "female", age in pink - contains "8") Peter | Male | 35 (name cell highlighted in green - starts with "p")
Method 3 - Using querySelector with Content Matching
Modern browsers support advanced CSS selectors in JavaScript's querySelector and querySelectorAll methods, allowing you to select elements based on their attributes or combine multiple selection criteria.
Example
Following example demonstrates using querySelectorAll to select divs with specific data attributes
<!DOCTYPE html>
<html>
<head>
<title>Advanced Div Selection</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; }
.product {
margin: 10px 0;
padding: 15px;
border: 2px solid #ddd;
border-radius: 5px;
}
.highlighted {
border-color: #e74c3c;
background-color: #fadbd8;
}
.featured {
border-color: #27ae60;
background-color: #d5f4e6;
}
</style>
</head>
<body>
<h2>Product Catalog</h2>
<div class="product" data-category="electronics" data-price="999">Smartphone</div>
<div class="product" data-category="clothing" data-price="49">T-Shirt</div>
<div class="product" data-category="electronics" data-price="1299">Laptop</div>
<div class="product" data-category="books" data-price="25">Programming Guide</div>
<button onclick="highlightExpensive()">Highlight Expensive Items (>$100)</button>
<button onclick="highlightElectronics()">Highlight Electronics</button>
<button onclick="resetHighlighting()">Reset</button>
<script>
function highlightExpensive() {
resetHighlighting();
const products = document.querySelectorAll('.product');
products.forEach(product => {
const price = parseInt(product.dataset.price);
if (price > 100) {
product.classList.add('highlighted');
}
});
}
function highlightElectronics() {
resetHighlighting();
const electronics = document.querySelectorAll('.product[data-category="electronics"]');
electronics.forEach(product => {
product.classList.add('featured');
});
}
function resetHighlighting() {
const allProducts = document.querySelectorAll('.product');
allProducts.forEach(product => {
product.classList.remove('highlighted', 'featured');
});
}
</script>
</body>
</html>
The buttons allow you to dynamically select and highlight different product categories based on their data attributes. Expensive items get a red highlight, while electronics get a green highlight.
Comparison of Selection Methods
Following table compares the different methods for selecting divs with specific content
| Method | Best For | Advantages | Limitations |
|---|---|---|---|
| JavaScript Text Content | Dynamic content matching | Flexible, can match partial text, case-insensitive options | Requires JavaScript execution, slower for large DOM |
| CSS Attribute Selectors | Static styling based on attributes | Fast, no JavaScript needed, works with CSS | Requires predefined data attributes |
| querySelector with Attributes | Complex selection criteria | Combines CSS selector power with JavaScript flexibility | Limited to attribute-based selection |
Best Practices
When selecting divs based on content, consider these best practices
Use data attributes Add custom
data-*attributes to elements for reliable selection rather than depending solely on text content.Normalize text content Use
trim()and consider case sensitivity when matching text content.Performance considerations For large documents, CSS attribute selectors are faster than JavaScript loops.
Semantic HTML Use appropriate HTML elements and classes to make selection more reliable and maintainable.
Conclusion
Selecting divs with specific HTML content can be accomplished through JavaScript text content matching, CSS attribute selectors, or modern querySelector methods. CSS attribute selectors offer the best performance for static content, while JavaScript methods provide more flexibility for dynamic scenarios. Choose the method that best fits your specific use case and performance requirements.
