AirelleJab AirelleJab - 3 months ago 14
HTML Question

Insert result of the function to div attribute

I'm completely new to HTML and JavaScript. I need to use 3Dmol.js so I followed the tutorial and I have a working piece of code:



<script src="http://3Dmol.csb.pitt.edu/build/3Dmol-min.js"></script>

<div id="element1" style="height: 400px; width: 400px; position: relative;" class='viewer_3Dmoljs' data-pdb='1a5j' data-backgroundcolor='0xffffff' data-style='cartoon' data-select1='resi:10' data-style1='stick:color=0x00FFFF'>
</div>





I would like to run a function that returns some value and puts it in data-select1='resi:x', where x is this value.

<script>
function a(x) {
return x;
}
</script>


So if I run:

a(2);


The div changes to:



<script src="http://3Dmol.csb.pitt.edu/build/3Dmol-min.js"></script>

<div id="element1" style="height: 400px; width: 400px; position: relative;" class='viewer_3Dmoljs' data-pdb='1a5j' data-backgroundcolor='0xffffff' data-style='cartoon' data-select1='resi:2' data-style1='stick:color=0x00FFFF'>
</div>





What's the easiest way to do that?

Answer

Use HTMLElement.dataset to set the data-select1 attribute

function a(x) {

    var el = document.getElementById('element1')
	
    // will set `data-select1`
    el.dataset.select1 = 'resi:'+x

    return x;
}

a(2);
<script src="http://3Dmol.csb.pitt.edu/build/3Dmol-min.js"></script>

<div id="element1" style="height: 400px; width: 400px; position: relative;" class='viewer_3Dmoljs' data-pdb='1a5j' data-backgroundcolor='0xffffff' data-style='cartoon' data-select1='resi:10' data-style1='stick:color=0x00FFFF'>
</div>

Comments