Issue
I am trying to add styles to To-do items on my web page using their id field.
<body>
<h1><%- dayType %></h1>
<ul class="tasks">
<% for(i = 0 ; i < data.length ; i++){ %>
<input id='label-<%-i+1%>' type='checkbox'/>
<label for="label-<%-i+1%>"><li><%- data[i] %></li></label>
<% } %>
<li>
<form action="/" method="post">
<input type="text" placeholder="Enter To Do Item" name="items">
<input type="submit" value="Submit">
</form>
</li>
</ul>
In the code where I am using for loops, there is a checkbox and label to which I am adding styles. My css looks like this:
#label-1:checked ~ label[for=label-1],
#label-2:checked ~ label[for=label-2],
#label-3:checked ~ label[for=label-3],
#label-4:checked ~ label[for=label-4],
#label-5:checked ~ label[for=label-5]{
background: #6d335c;
border-bottom: 1px solid #34495E;
color: #d37b79;
}
When a checkbox of a to do item is checked, the corresponding to do item's style is changed. However, I am able to only change the style of a limited number of to do items because in css, we have to hard code the style for each To do item's id. I want the website to enter as many to do items as possible and their checkboxes to run perfectly. How to achieve this?
Solution
You could use a selector which will select all elements with an attribute starting with a specified string
[attr^=value]
see MDN
In your case:
*[id^="label-"]:checked ~ label[for^="label-"]{
background: #6d335c;
border-bottom: 1px solid #34495E;
color: #d37b79;
}
However, unless there is a reason why you have to distinguish between those elements by id, I'd suggest you use a class instead. Then you can be absolutely sure you are getting the right set of elements.
Answered By - A Haworth
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.