javascript - Set Data Attribute using DataSet API -


following way data attribute tag using dataset api.

<div data-color="red">apple</div>  var color = document.queryselector('div').dataset.color 
  1. how set data attribute?
  2. can create new data attributes?
  3. will automatically appended element?

please provide answer example.

thanks.

  1. you can set data- attribute via same dataset mentioned or element.setattribute()
  2. yes, demonstrated in code example below. can dataset or setattribute.
  3. yup. css can style them because of this. see div[data-price]:after style in example.

var div = document.queryselector('div');  var data = div.dataset;    div.innerhtml += ' ' + data.color;    data.color = 'yellow';    div.innerhtml += '; ' + data.color + '. <br/>';    data.type = 'golden delicious';    div.setattribute('data-price', '$1.00');    div.innerhtml += 'this div has following attribute/value pairs:';    (var = 0; < div.attributes.length; i++) {    var attr = div.attributes[i];    div.innerhtml += '<br/>' + attr.name + '=' + attr.value;  }    div.innerhtml += '<br/>this div has following dataset key/value pairs:';    (var key in data) {    div.innerhtml += '<br/>' + key + '=' + data[key];  }
div[data-color=red] {    color: red;  }  div[data-color=yellow] {    color: goldenrod;  }  div[data-price]:after {    content: attr(data-price);    color: green;  }
<div data-color="red">apple</div>


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -