如何在JavaScript中为元素添加样式?基于类名选择元素并设置样式的实现方案
Hey there! Let's walk through how to style your generated <li> elements and cover the general ways to add styles with JavaScript.
1. The Simplest Approach: Use CSS Directly
Since your generated <li> elements already have clear class names (text and ayahNumber), the easiest and most maintainable way to style them is with plain CSS. Just add these rules to your stylesheet:
/* Style for the verse text */ .text { font-size: 1.2rem; line-height: 1.6; color: #2d3748; margin-bottom: 0.5rem; } /* Style for the ayah number */ .ayahNumber { font-weight: bold; color: #e53e3e; margin-left: 1rem; }
Once you inject your versesHtml into the DOM, these styles will automatically apply to the matching elements—no extra JavaScript needed!
2. Styling via JavaScript (For Dynamic Scenarios)
If you need to apply styles dynamically (like based on user interaction or changing data), here are two solid methods:
a. Modify Inline Styles Directly
First, make sure your generated HTML has been added to the DOM. Then use document.querySelectorAll to target the elements and update their style properties:
// Target all .text elements and apply styles document.querySelectorAll('.text').forEach(element => { element.style.fontSize = '1.2rem'; element.style.lineHeight = '1.6'; element.style.color = '#2d3748'; }); // Target all .ayahNumber elements and apply styles document.querySelectorAll('.ayahNumber').forEach(element => { element.style.fontWeight = 'bold'; element.style.color = '#e53e3e'; element.style.marginLeft = '1rem'; });
Note: Inline styles have high specificity, so they'll override most external CSS rules. Use this for one-off dynamic changes.
b. Add Predefined CSS Classes
A better practice is to define your styles in CSS first, then use JavaScript to add the classes to your elements. This keeps your styles organized and separate from your logic:
/* Predefined classes in your stylesheet */ .verse-text { font-size: 1.2rem; line-height: 1.6; color: #2d3748; } .verse-number { font-weight: bold; color: #e53e3e; margin-left: 1rem; }
Then in JavaScript:
// Add the class to all .text elements document.querySelectorAll('.text').forEach(element => { element.classList.add('verse-text'); }); // Add the class to all .ayahNumber elements document.querySelectorAll('.ayahNumber').forEach(element => { element.classList.add('verse-number'); });
You can also use classList.remove() or classList.toggle() to adjust styles later if needed.
3. General Methods for Adding Styles in JavaScript
Here are all the common ways to apply styles with JS, depending on your use case:
Inline Style Updates: Modify individual style properties directly (great for quick, one-off changes):
element.style.backgroundColor = '#f7fafc'; element.style.padding = '1rem';Remember to use camelCase for property names (e.g.,
backgroundColorinstead ofbackground-color).Class List Manipulation: Use
classListmethods to add/remove/toggle CSS classes (most recommended for maintainability):element.classList.add('active'); element.classList.remove('inactive'); element.classList.toggle('highlighted'); // Switches the class on/offDynamic Style Sheets: Create a new
<style>tag and inject it into the document head for bulk style rules:const styleSheet = document.createElement('style'); styleSheet.textContent = ` .text { font-size: 1.2rem; } .ayahNumber { color: #e53e3e; } `; document.head.appendChild(styleSheet);Set Style Attribute: Directly set the entire
styleattribute as a string (not recommended for large styles, since it's hard to edit):element.setAttribute('style', 'font-size: 1.2rem; color: #2d3748;');
Quick Fix for Your Existing Code
I noticed a small issue in your HTML generation code: the ayah number is wrapped in extra curly braces. Update it to this to render the number correctly:
const versesHtml = ` ${verses.map( (v, i) => `<li class="text">${v.text_uthmani}</li> <li class="ayahNumber">${i+1}</li>`).join(' ')} `;
The original code would output {1} instead of 1—removing the outer curly braces fixes that.
内容的提问来源于stack exchange,提问作者Rahaf

