ameli
ameli

Reputation: 73

add different data-attribute to elements, creating by js

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?

Upvotes: 1

Views: 434

Answers (1)

prathameshk73
prathameshk73

Reputation: 1088

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>

Upvotes: 1

Related Questions