简体   繁体   中英

How to completely remove the canvas element with Jquery/JavaScript?

I have a canvas object that loads on my page dynamically from a jQuery plugin. It has no wrapper, no id or class associated to it. But I need to remove it after

$(window).resize(function)() {...} 

takes place. I have tried using jQuery's

...next().remove(); 

technique, so that the neighboring div element can remove it from the DOM, but I am getting issues. specifically, additional elements on my page are also getting removed. Is there a healthy way to about this?

Thanks!

If you are not using multiple canvas elements, simply

$('canvas').remove();

Will remove all matched elements on the page. http://jsfiddle.net/vj6NP/

If you do have multiple canvas on the page and would like to remove only one, you could select which one to remove using nth-of-type .

For example to remove the first instance http://jsfiddle.net/vj6NP/3/ : -

$('canvas:nth-of-type(1)').remove();

How many canvas elements do you have on the page? If there is only one; and you don't plan to ever add any in the future it might be simplest just to do

var dynamic_canvas = $('canvas');
if(dynamic_canvas) dynamic_canvas.remove();

The easiest way is to keep a reference to the canvas element added to the document then remove it using JQuery:

this.canvas = document.createElement('canvas');
//later...
$(this.canvas).remove();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM