I have to write down a code that allows me to change an attribute of an element. I want to do this through buttons. Basically, the forward button has to choose the next element of a javascript array. The backward button, instead, the previous one. I tried something like this with poor results:
<!--Let us suppose that we have a paragraph-->
<p id='par' style='color:green'>Something</p>
<button onclick="forward()">TGo On !</button>
<!-- The backward button will follow a similar logic-->
<script>
function forward() {
const colors = ['color:pink', 'color': green ','
color: blue ','
color: red '];
if (colors.indexOf(document.getElementById('par').getAttribute('style')) < colors.length)
document.getElementById('par').setAttribute('style', colors[colors.indexOf(document.getElementById('par').getAttribute('style')) + 1])
else {}
}
</script>
Thank you in advance
Use the style property instead of the HTML attribute to edit styles via javascript.
function forward() {
const paragraph = document.getElementById('par');
const colors = ['pink', 'green', 'blue', 'red'];
var current_color_index = colors.indexOf(paragraph.style.color);
var new_color_index = current_color_index === colors.length - 1 ? 0 : current_color_index+1;
paragraph.style.color = colors[new_color_index];
}
<p id='par' style='color:green'>Something</p>
<button onclick="forward()">TGo On !</button>