I am looking to extract the values from a loop and manipulate them outside of it.
Specifically, I want to target all elements with the class "testY" and only apply changes to the last one.
let classes = Array.from(document.getElementsByClassName("testY"));
classes.forEach(function (looped, i) {
loopclass = looped;
loopclass.style.color = "blue";
return loopclass;
});
loopclass.style.color = "orange";
However, only the last element is turning orange. How can I recycle these elements without being confined within the loop?
---- EDIT 1
Building on the previous code, I want to retrieve the classes and manipulate them outside of the loop.
Here is another example based on the suggestions:
let classeslist = Array.from(document.getElementsByClassName("testY"));
let classes = classeslist.map( (el) => {
loopedclass = el;
return loopedclass
});
loopedclass.style.color = "orange";
Even with this approach, only the last class is affected.
---- EDIT 2.B
We're getting there.
The concept works but chaining remains an issue.
I tried to incorporate the FrankerZ constructor into the code, but got stuck.
Now, the question revolves around libraries... How do you concatenate the results of functions?
LIBS:
actions = {
showError: (elem) => {
elem.style.color = 'red';
},
highlight: (elem) => {
elem.style.color = 'orange';
elem.style.fontSize = '1.2em;';
}
}
class Core {
find(subject) //works
{
let name;
if (subject.startsWith("#")) {
...
}
if (subject.startsWith(".")) {
name = subject.split(".")[1];
find = [...document.getElementsByClassName(name)];
}
if (subject.startsWith("[")) {
...
}
return find;
}
actionfor(target, todo) //works
{
target.forEach(actions[todo]);
}
loop(todo)
{
alert("direct todo");
???.forEach(actions[todo]);
}
}
const core = new Core();
SCRIPT:
(function () {
//indirect action // works!
var X = core.find(".test_X");
core.actionfor(X, "showError");
//direct action //issue!
core.find(".test_Y").loop("highlight");
})();
HTML:
<div class="test_X">SIMPLE TEST CLASS</div>
<div class="test_X">SIMPLE TEST CLASS</div>
<div class="test_X">SIMPLE TEST CLASS</div>
<div class="test_Y">SIMPLE TEST CLASS</div>
<div class="test_Y">SIMPLE TEST CLASS</div>
<div class="test_Y">SIMPLE TEST CLASS</div>