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
- how set data attribute?
- can create new data attributes?
- will automatically appended element?
please provide answer example.
thanks.
- you can set
data-
attribute via samedataset
mentioned orelement.setattribute()
- yes, demonstrated in code example below. can
dataset
orsetattribute
. - 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
Post a Comment