Add an id value for a canvas element in jquery

三世轮回 提交于 2020-01-05 21:13:17

问题


How I dynamically add an id value for a canvas object in jQuery?

HTML

<div id="obj">
    <canvas></canvas>
    <canvas></canvas>
</div>

How do I change the second canvas object value with somename?

Expected result:

<canvas id="somename"></canvas>

回答1:


The $() function returns an array of matching DOM elements so you can just assign to the id property of the second element:

$('#obj canvas')[1].id = 'somename';



回答2:


Try this:

$("#obj canvas").slice(1).attr("id","somename");


来源:https://stackoverflow.com/questions/4976625/add-an-id-value-for-a-canvas-element-in-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!