Home > Net >  Making js pick up HTML code inside data attribute?
Making js pick up HTML code inside data attribute?

Time:06-21

I have a piece of html code in data attribute.

<a href="#" data-type="video" data-video='<div ><div ><video id="player" playsinline width="960"  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!

CodePudding user response:

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)

CodePudding user response:

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"
  • Related