How to set ejs data to data atribute and parse it in client side js?

Viewed 14

I am trying to send leaderboard data from the server to the client side javaScript. Heres my server side javascript.

const leaderboard = [[dog,cat],[car,bus],[foo,bar]]

const toJson = JSON.stringify(leaderboard)
        res.render('games/dodge.ejs', {
                leaderboard: toJson
 })    

Here is how my ejs file recives it

<div data-leaderboard="<%= leaderboard%>"></div>

and then there is the clientside js dodge_leaderboards.js

const leaderboardData = document.querySelector("[data-leaderboard]")

console.log(leaderboardData)

When I run this code it returns an error that says Uncaught SyntaxError: Identifier 'leaderboardData' has already been declared (at dodge_leaderboards.js:1:1) Also the console.log returns null.

I am trying to assing the arrays inside the big array to own variables, but now I am having problems with just a simple console.log. What do you think is causing the problem, I am also curios to hear how to parse the array.

1 Answers

Okay I got it working I forget to put ".dataset.leaderboard" after the leaderboardData

const leaderboardData = document.querySelector("[data-leaderboard]")

console.log(leaderboardData.dataset.leaderboard)

Related