0

I want to get data from one div and insert the data to a new div using data attribute.

//get data from old div as JSON
var data = JSON.parse(document.getElementById('video_data').getAttribute('data-video'));

This is the div from where I get data. enter image description here

//insert the data to the new div
document.getElementById('i').insertAdjacentHTML('afterbegin', '<div class="video_wrap update" video_name="' + data.video_name + '" data-video="' + JSON.stringify(data) + '"><div class="content"><div class="title_wrap infinite_wrap"><div class="quality uninfinite">∞</div></div><div class="img_wrap"><img src="https://i.ytimg.com/vi/' + data.yt_id + '/hqdefault.jpg"></div><div class="title_wrap"><div class="title">' + data.title + '</div></div></div></div>');

This is what I get after inserting the new div. enter image description here

You can see that even the colour is not correct

What is the problem?

2 Answers 2

2

Json stringify is just turning it into a string. You need to escape the double quotes in the resulting string so that it will play nice when rendered

I could probably also globally replace the " with ' if you are confident there are no single quotes in you data?

Oh as an afterthought If you construct the div in JavaScript and you only support newer browsers you should be able to do

El.dataset.video = your json string
Sign up to request clarification or add additional context in comments.

4 Comments

I did this: data.replace(/"/g, '\\"') and no result.
You need to do that to the result of json.stringify(data)
I did that var a = JSON.stringify(data); var b = a.replace(/"/g, '\\"'); and than I inserted b.
Hrm. Replace with single quote then? A bit of googling shows that HTML doesn't respect the \ as an escape char.
0
document.getElementById('i').insertAdjacentHTML('afterbegin', '<div class="video_wrap update" video_name="' + data.video_name + '"><div class="content"><div class="title_wrap infinite_wrap"><div class="quality uninfinite">&infin;</div></div><div class="img_wrap"><img src="https://i.ytimg.com/vi/' + data.yt_id + '/hqdefault.jpg"></div><div class="title_wrap"><div class="title">' + data.title + '</div></div></div></div>');
document.getElementById('i').firstChild.setAttribute('data-video', JSON.stringify(data));

This fixed the error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.