0

I am new to jquery, I tried to access the input element via id , I see it returns "undefined" I wrapped it inside document.ready; result is the same, here is the code snippet

let input;

function maintest() {
   input = $("<input>").attr({"id":"test"});
   input.append("#mainDiv");
   $(document).ready( function(){
     alert($("#test").html());
   });

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body onload="maintest()">
  <div id="mainDiv"></div>
</body>

I am surprised it shows "undefined" instead of showing the whole input element when I alert

1
  • What is the value of input when you use $(input).attr({"id":"test"})? Commented Feb 12, 2020 at 18:59

1 Answer 1

3

You have several problems:

  1. You never assigned anything to input before calling $(input). If you're trying to create an input element, you need to put a literal string <input> in the arguments.
  2. You should use appendTo(), not append().
  3. input elements aren't containers, they don't have any HTML in them, so .html() won't return anything (it's equivalent to .innerHTML, not .outerHTML). I changed the script to use $("#mainDiv").html(), then it show the <input> contained within it.

function maintest() {
  let input = $("<input>").attr({
    "id": "test"
  });
  input.appendTo("#mainDiv");
  $(document).ready(function() {
    alert($("#mainDiv").html());
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<body onload="maintest()">
  <div id="mainDiv"></div>
</body>

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

3 Comments

Thanks Barmar but why wouldn't alert($("#test").html()); output anything?
What do you expect it to output?
.html() is equivalent to .innerHTML, it returns the contents of the element, not the element itself.

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.