views:

56

answers:

2

Instead of .show()'ing and .hide()'ing (or .toggle()'ing for that matter), is there any way to "toggle" a .remove() function?

I realize .remove() literally removes elements from the DOM, so it sounds difficult to magically replace the removed elements once they're gone, but is there a way of faking it?

Note: They must be removed from the DOM so that they are ignored by screen readers (AFAIK screen readers do not respect .show() and .hide()).

Thanks.

--- EDIT ---

OK, so .detach() might work for me. If my markup is:

<a href="#">Toggle images</a>

<p><span>Some text here</span><img src='image1.png'/><img src='image2.png'/></p>
<p><span>Some more text</span><img src='image2.png'/></p>
<p><span>Even more text</span><img src='image5.png'/><img src='image1.png'/>
  <img src='image5.png'/></p>

And by clicking the anchor it would remove all images, and clicking again would restore. Using .detach() how would it work?

--- EDIT #2 ---

As thenduks pointed out, screen readers in fact do respect display: none; which changes my question a bit. I ended up with a simple toggle code. Thanks!

A: 

You can save the DOM element(s) to a variable to be added back again later.

Check example here.

John Strickler
there's a great chance that `$('p').remove();` will return null so I don't think `savedNodes = $('p').remove();` would work but that's the right idea
hunter
+3  A: 

You could try using jQuery 1.4's recent addition: detach to remove them and then re-add them later.

thenduks
! ! ! perfect ! ! !
hunter
Yea pretty handy. I had some sorting code on a side project that was sped up immensely after jQuery 1.4 came out and I started using this.
thenduks
.detach() would work. I updated my question slightly, since I've never used it before and the API sample only confused me :)
farkenfooken
You'll meet the same changes as you would with `.remove()`. The only difference between the two is that `detach()` retains data like event handlers. OP was concerned with how to easily re-insert back into the original position.
patrick dw
If you want to put them back in the original position then I fail to see why you wouldn't just hide them and not remove them in the first place.
thenduks
@thenduks - Take another look at the question: *"Note: They must be removed from the DOM so that they are ignored by screen readers (AFAIK screen readers do not respect .show() and .hide())."* I don't know if that's correct about screen readers, but this was OPs reason for this approach.
patrick dw
@patrick dw - yep, you're right.
farkenfooken
Screen readers normally wont execute much javascript at all. Also, in my experience screen readers _do_ ignore elements that are hidden (display: none).
thenduks
It's not true that they don't respect javascript at all -- depending on the screen reader, they actually do. It is true, in fact, that they respect `display: none;` -- Therefore the scope of my question changes and I can simply use `.toggle()`. Thanks.
farkenfooken