Search code examples
javascriptattributescountdownattr

How to manipulate an custom attribute javascript


I'm struggling with this script where I need to "select" an attribute of a HTML tag.

Its an application that when I click on button would start this countdown but

I'm using and customized countdown that I found. And it has this attribute named "data-date"

<div data-date="<?php echo date('Y/m/d H:i:s', $today); ?>" id="count-down"></div>

I know that I would have problems with <?php echo date('Y/m/d H:i:s', $today); ?>

but that's okay I think I did it solve it to change to javascript.

So this is how my script got

                var oldDateObj = new Date();
                var time = new Date();
                time.setTime(oldDateObj.getTime() + (<?=$time?> * 1000)); //adding time to the current time

                //How it should get

                //<h2>Countdown</h2>
                //<div data-date="<?php //echo date('Y/m/d H:i:s', $today); ?>" id="count-down"></div>

                document.getElementById("coluna1").innerHTML = "";

                let temp = document.createElement('h2');
                temp.innerHTML = 'Temporizador';


                let div1 = document.createElement('div');
                div1.data-date = time;                         //where the error occurs 
                div1.id = "count-down";


                document.getElementById("coluna1").appendChild(temp);
                document.getElementById("coluna1").appendChild(div1);

The error is an Uncaught syntax error: Invalid left-hand side on assignment

So with someone has any idea to help me out, share it please :)


Solution

  • In JS, property names that aren't valid identifiers cannot be accessed using the dot syntax.

    For regular JS object, you could bypass this limitation by using the bracket syntax, but that won't work for HTML elements (it will set the property, but the property won't become the attribute of the element).

    However, there's a way to manipulate data-* attributes of an element using the dataset property:

    div1.dataset.date = time;