Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jquery selector having element type and ID

Tags:

jquery

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?

like image 414
Manoj Avatar asked Sep 30 '11 10:09

Manoj


People also ask

How do you select element by id in jQuery?

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.

How do you select an element with ID and class?

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.

How do you select an element with ID data '?

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.


2 Answers

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

$("textarea#myTextArea").val(text);
like image 171
Daniel A. White Avatar answered Oct 05 '22 22:10

Daniel A. White


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.

like image 29
Clive Avatar answered Oct 06 '22 00:10

Clive