I have this HTML:
<div >
<ul >
<li data-element="element A">element A</li>
<li data-element="element B">element B</li>
<li data-element="element C">element C</li>
</ul>
</div>
This is my code:
const data = $('.wrapper .list . element').data('element');
console.log(data)
The result in the console is only the first element - element A. But I need each of them. Because I want to use them next way, e.g.:
if (data === 'element A') return $('li').css('color', 'red');
if (data === 'element B') return $('li').css('color', 'blue');
if (data === 'element C') return $('li').css('color', 'green');
CodePudding user response:
- Loop your elements using the .each() jQuery method
- Fix your selectors,
". element"
is invalid. Should be".element"
or rather:"[data-element]"
$(".list [data-element]").each(function() {
console.log($(this).data("element"));
});
but here's my suggestion how to tackle the task using an Object as colors reference:
const dataColors = {
"element A": "red",
"element B": "blue",
"element C": "green",
};
$("[data-element]").each((i, el) => {
$(el).css({"color": dataColors[$(el).data("element")]});
});
<div >
<ul >
<li data-element="element A">element A</li>
<li data-element="element B">element B</li>
<li data-element="element C">element C</li>
</ul>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
in vanilla JavaScript it's also pretty simple:
const dataColors = {
"element A": "red",
"element B": "blue",
"element C": "green",
};
const ELS_data = document.querySelectorAll("[data-element]");
ELS_data.forEach(el => el.style.color = dataColors[el.dataset.element]);
<div >
<ul >
<li data-element="element A">element A</li>
<li data-element="element B">element B</li>
<li data-element="element C">element C</li>
</ul>
</div>
Anyways, it seems quite odd to use JS for that task - with hardcoded values of colors.
It would make sense if you had something dynamic, values that JavaScript has to consume from a HTML attribute like data-color="orange"
const ELS_data = document.querySelectorAll("[data-color]");
ELS_data.forEach(el => el.style.color = el.dataset.color);
<div >
<ul >
<li data-color="red">element A</li>
<li data-color="hsl(200, 80%, 70%)">element B</li>
<li data-color="#fb0">element C</li>
</ul>
</div>
Otherwise, CSS would suffice:
[data-element="element A"] { color: red; }
[data-element="element B"] { color: blue; }
[data-element="element C"] { color: green; }
/* etc... */
because there's nothing dynamic.