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.

5
  • 2
    Pretty much yeah - it's redundant tho, passing html to the .html function completely overwrites the HTML anyways. Commented Oct 6, 2014 at 16:08
  • 2
    $("#result").html(result); will be enough... Commented Oct 6, 2014 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? Commented Oct 6, 2014 at 16:09
  • woah, easy chaps @FelixKling... just want the fastest answer that's why i posted a question here... Commented Oct 6, 2014 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? Commented Oct 6, 2014 at 16:22

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

That doesn't answer the OP's question though.
-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 =)

1 Comment

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.

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.