-2

I have a piece of html code in data attribute.

<a href="#" data-type="video" data-video='<div class="wrapper"><div class="video-wrapper"><video id="player" playsinline width="960" class="pswp__video" controls data-poster="img/poster.jpg"><source src="video/soulmv-low.mp4" type="video/mp4"></video></div></div>'></a>

Is there any way to make js pick up the code inside data attribute and modify it, as normal?

Thanks!

soulmv
  • 13
  • 3
  • 3
    I have no idea what you are asking for exactly. What are you trying to do? Read the attribute and what? – epascarello Jun 20 '22 at 14:55
  • 2
    Why would there be HTML inside an attribute? What are you trying to achieve? – Reyno Jun 20 '22 at 14:56
  • I would expect HTML within an attribute to itself be invalid HTML. At the very least it should be HTML-encoded as a string. Though even then I suspect there's a better way to achieve whatever it is you're trying to achieve. – David Jun 20 '22 at 14:57
  • Basically im trying to make js parse the code inside data attribute and change it as it was a normal code from html body... Sorry, Im not super experienced in js, so might have messed up the explanation :) – soulmv Jun 20 '22 at 15:08
  • 1
    https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString – epascarello Jun 20 '22 at 15:33
  • Does this answer your question? [How can I get the values of data attributes in JavaScript code?](https://stackoverflow.com/questions/33760520/how-can-i-get-the-values-of-data-attributes-in-javascript-code) – gre_gor Nov 13 '22 at 19:59

2 Answers2

0

If you want to load an html as an DOM Element to modify is easily instead of an string, you could do the following:

const link = document.querySelector('a')

const dataVideoAttribute = link.getAttribute('data-video')

const dataVideoElement = createElementFromString(dataVideoAttribute)

The helper function to create JS Object is descrbied bellow

/**
 * Create a new HTML Object from an HTML code as string
 * and returns the object.
 * 
 * @params elementAsString: HTML code as a raw string
 *
 * @returns object: HTML Element created from raw string
 */
function createElementFromString(elementAsString) {
  var div = document.createElement('div');
  div.innerHTML = elementAsString.trim();

  // Change this to div.childNodes to support multiple top-level nodes.
  return div.firstChild;
}

then, you can do normal routines with your JS code, for exmaple:

dataVideoElement.setAttribute('new-att', '1')

If you want to update and save on html attributes you could:

link.getAttribute('data-video', dataVideoElement.outerHTML)
-1

To get the data attribute, for example if the attribute is data-type="video"

const type = document.getElementById('item1').dataset.type;

To set it

document.getElementById('item1').dataset.type = "mp3"
Mina
  • 14,386
  • 3
  • 13
  • 26