1

Please, help. How can I set the different data attribute to the elements, which creating by js with using forEach?

const buttons = ['%', 'C', 'DEL', '÷', '1', '2', '3', '*', '4', '5', '6', '+', '7', '8', '9', '-', '.', '0', '='];
buttons.forEach(button => {
    const btn = document.createElement('button');
    btn.innerHTML = button;
    fragment.appendChild(btn);
});

in the end I should get

<button data-all-clear class="span-two">AC</button>
    <button data-delete>DEL</button>
    <button data-operation>÷</button>
    <button data-number>1</button>
    <button data-number>2</button>

How can it possible?

1 Answer 1

1

You need to check ASCII character of each element in an array using 'charCodeAt' method. Please check working example below.

<!DOCTYPE html>
<html>

<head>
    <title>Ascii</title>
    
    <script>
        window.onload = function () {
            const buttons = ['%', 'C', 'DEL', '÷', '1', '2', '3', '*', '4', '5', '6', '+', '7', '8', '9', '-', '.', '0', '='];
            const fragment = document.getElementById('fragment');
            buttons.forEach(button => {
                const btn = document.createElement('button');
                const charCode = button.charCodeAt();
                if (charCode >=37 && charCode <= 47) {
                    btn.setAttribute('data-operation', button);
                } else if (charCode >=48 && charCode <= 57) {
                    btn.setAttribute('data-number', button);
                } else if ((charCode >=97 && charCode <= 122)
                   || (charCode >=65 && charCode <= 90)) {
                    btn.setAttribute('data-character', button);
                } else {
                    btn.setAttribute('data-delete', button);
                }
                btn.innerHTML = button;
                fragment.appendChild(btn);
            });
        };
    </script>
</head>

<body>
    <br /><br />

    <div id="fragment">

    </div>
</body>

</html>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.