Find an element by partial ID in jQuery?

Jquery

Jquery Problem Overview


I have an element on my page, where i only will know part of its id, e.g. _moComments_:

id="MainContent_listSelectedDays_listDayBanks_0_moComments_0"

How can i find an element by partial id (e.g. using jQuery)?

For example (jsFiddle):

<input type="text" id="MainContent_listSelectedDays_listDayBanks_0_moComments_0">

with script

$('[id=_moComments_]').val("Found it");

Bonus Reading

Jquery Solutions


Solution 1 - Jquery

You could use the "Attribute Contains Selector":

$('[id*="_moComments_"]')

However you'd probably be better off by simply adding a class or a custom [data-*] attribute and selecting based on that.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIan BoydView Question on Stackoverflow
Solution 1 - JqueryzzzzBovView Answer on Stackoverflow