0

is there a best way of "clearing" html inside an element using jQuery? I use .html(null) but is .html("") more efficient. And is there an even better/nicer way of achieving this?

1

2 Answers 2

10

Is there a reason for not just using .empty()?

And, incidentally, if your question is about 'efficiency,' so long as efficiency is broadly comparable with speed, then might I suggest JS Perf for self-testing?

Incidentally, in a JS Perf comparison, with Chromium 18/Ubuntu 11.04, .empty() seems to be consistently the faster approach. References:

Further to the above; if you don't mind using plain ol' native JavaScript, it's even faster (on my Samsung II the DOM runs at ~82k ops/sec, on my desktop (nothing special) in Chromium 18/Ubuntu 11.04, the DOM runs at: ~860k ops/sec, as opposed to .empty() (the next fastest) at 8.4k ops/sec).

A DOM-based approach:

var list = document.getElementsByTagName('ul')[0];
while (list.firstChild) {
  list.removeChild(list.firstChild);
}

JS Perf comparison of all above approaches.

References:

Sign up to request clarification or add additional context in comments.

3 Comments

With null as value he is using empty - indirectly jsapi.info/jquery/1.7.1/jQuery.fn.html
thanks for your reply, do you know if there is an equivalent for setting empty .val()??
You're very welcome, I'm glad to have been of help =) as to the val() question, then no, I don't believe there is, in that case.
1

http://api.jquery.com/empty/

provided by jQuery

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.