0

im newbie in jquery/javascript and got this code below:

$("#result").empty().html(result);

can someone explain the code. correct me if im wrong but i think, it explains that it should empty first before displaying another result in the id of result?

Thank you.

  • 2
    Pretty much yeah - it's redundant tho, passing html to the `.html` function completely overwrites the HTML anyways. – tymeJV Oct 06 '14 at 16:08
  • 2
    `$("#result").html(result);` will be enough... – Arun P Johny Oct 06 '14 at 16:09
  • 2
    Have you read the documentation of `empty` and `html`? Is there anything unclear about what the functions are doing? Or are you asking about method chaining works, i.e. `foo().bar()`? In that case, see [how does jquery chaining work?](http://stackoverflow.com/q/7475336/218196) – Felix Kling Oct 06 '14 at 16:09
  • woah, easy chaps @FelixKling... just want the fastest answer that's why i posted a question here... – Jed Monsanto Oct 06 '14 at 16:19
  • OK, to make sure I understood correctly: You want to know what `empty` and `html` are doing and thought you will get a faster answer here than looking the functions up in the documentation? – Felix Kling Oct 06 '14 at 16:22

2 Answers2

2

.html() Set the HTML contents of each element in the set of matched elements. Thus you do not need to explicitly empty it as you are already overwriting the content. You can simply use:

$("#result").html(result);
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
-1

$("#result").empty() will remove everything inside #result. $("#result").html() will retrieve everything inside #result

I think what you need is .text(), .val() or .append()

$("#result").append(result) will populate #result with the data from result, removing what was already inside #result. I don't know if i make myself clear, i'm new here =)

maxito
  • 21
  • 4
  • The `.html()` overload gets the content, but `.html(content)` sets the content. The `append` method won't remove what's already there, it will append elements to the existing ones. – Guffa Oct 06 '14 at 16:17