-3

I have the following element below that has a data attribute that contains a json string. I am unable to retrieve the json string, instead it is returning the opening bracket of the json string. Please see below.

console.log(document.getElementById('elem').getAttribute('data-hashtags'));
<input id="elem" data-hashtags="["john","barclays-statements","hmrc","laptop","tesco","meat","dinner","drinks","food","cleaning-products","taxi","lunch"]">
Colin
  • 1,112
  • 1
  • 16
  • 27
eddy123
  • 43
  • 11
  • 1
    `data-hashtags='["john","barclays-statements","hmrc","laptop","tesco","meat","dinner","drinks","food","cleaning-products","taxi","lunch"]'` try this. – Özgür Can Karagöz Jul 23 '18 at 09:37
  • @ÖzgürCanKaragöz if you would like to put that as an answer i can accept it. thanks for your help – eddy123 Jul 23 '18 at 09:41

1 Answers1

0

You mixed up the quotes.

It should be like this:

<input id="elem" data-hashtags="['john','barclays-statements','hmrc','laptop','tesco','meat','dinner','drinks','food','cleaning-products','taxi','lunch']">

Not like this:

<input id="elem" data-hashtags="["john","barclays-statements","hmrc","laptop","tesco","meat","dinner","drinks","food","cleaning-products","taxi","lunch"]">

As you can see in the syntax highlighting, attributes are marked orange (e. g. data-hashtags), and values of attributes are blue (e. g. elem). The values of your attribute are also marked orange, that means they get interpreted as attributes themselves.

That's because after " the value "starts". With your second ", the value "ends", so the value is just a bracket [. According to that, the next attribute would be john with the value of , (missing = here, so it would be invalid anyways), and so on.

CodeF0x
  • 2,624
  • 6
  • 17
  • 28