Tengo que escribir un código que me permita cambiar un atributo de un elemento. Quiero hacer esto a través de botones. Básicamente, el botón de avance tiene que elegir el siguiente elemento de una matriz de JavaScript. El botón de retroceso, en cambio, el anterior. Intenté algo como esto con malos resultados:
<!--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>Gracias de antemano
Use la propiedad de style en lugar del atributo HTML para editar estilos a través de 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>