19

I'm using this selector $("textarea #myTextArea").val(text); and it's not working. If I remove the ID and use the class it's working. Why isn't jquery able to find the element here?

elena
  • 3,740
  • 5
  • 27
  • 38
Manoj
  • 5,542
  • 9
  • 54
  • 80
  • 4
    fyi, just the id is optimized in jquery - you will be slowing down the selector considerably – Daniel A. White Sep 30 '11 at 10:54
  • Daniel is right, you should use only $("myTextArea") instead of your selector. It directly uses javascript's getElementById() so it's fast and efficient. When using your selector, the script will select all elements (in this case textareas) and iterate through them until it finds the proper one. – Przemek Sep 30 '11 at 10:58
  • Yes, but I cannot do that as the same ID is used else where, in the same page, I know that's terrible, but I have to live with that. – Manoj Sep 30 '11 at 10:59
  • 1
    Why do you have to live with that? That's not valid HTML. Perhaps you are using IDs where classes may be more appropriate? – Kasaku Sep 30 '11 at 11:10

2 Answers2

46

Because of the space. With the space it says the #myTextArea within a textarea.

$("textarea#myTextArea").val(text);
Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • 1
    "textarea" is not just redundant. It is about 80% slower. Here, I created a test: http://jsperf.com/jquery-selector-performance-test123 – Alex from Jitbit Apr 01 '15 at 13:20
5

Just remove the space:

$("textarea#myTextArea").val(text);

At the moment you're trying to select an element with ID myTextArea that is a descendant element of a textarea

As Jared Farrish mentions in the comments removing the element type would be more efficient:

$("#myTextArea").val(text);

If your document is valid then every ID will only used be once so this is still correct.

Clive
  • 36,918
  • 8
  • 87
  • 113