0

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 :)

IndexError
  • 81
  • 7

2 Answers2

0

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;
FZs
  • 16,581
  • 13
  • 41
  • 50
  • @IndexError I'm glad that it helped. On the questions you've asked, you can accept the answer you find the most helpful using the grey tick symbol next to it. – FZs Mar 06 '21 at 16:19
0

data-date is not valid - the parser will interpret this probably as the subtract operator

To access fields with names like this try using this notation:

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

If you are using jQuery, you could access these data-* attributes like this:

<div id="count-down" data-date="xxx"/>


$("#count-down").data("date");

Here is more info

If you prefer to use plain JS - here's a documentation on dataset property

mehowthe
  • 761
  • 6
  • 14