I have a couple of pointers to make this a little easier to write and to improve your existing code.
First, lines 1 - 4 keep selecting your desired element over any over again - this means more DOM traversals, which is slower. All of the jQuery methods return the instance of the element(s), so you can "chain" your method calls like this:
$("#"+div_id).attr('contentEditable', true)
.css('color','#F00')
.css('cursor','Text');
Note: The line breaks here are insignificant.
Second, selectors of the form #myId
generally perform better than selectors of form tagnam#myId
, the reason being the first will map directly to document.getElementById
whereas the second will use document.getElementsByTagName
and then loop over them to find the one with the id.
So, back to your original question. My suggestion is to simply add a CSS class to your selected element, rather than setting inline styles with the call to .css()
. Then, there is no need to store your previous element in a hidden field like you've suggested.
Instead, you can simply just select the div
tags that have your selected class.
The key here is that your previous element, if any, will always have the CSS class you're adding.
Here's an example of what I'm getting at:
function edit_addon(div_id)
{
//step 1 - find your old element and clear the CSS
$('div.selected').removeClass('selected');
//step 2 - now, modify the div_id element
$("#"+div_id).attr('contentEditable', true)
.addClass('selected');
}