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?
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.
If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.
Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.
Because of the space. With the space it says the #myTextArea
within a textarea
.
$("textarea#myTextArea").val(text);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With