I have a web-components guide which has a list of web-components constructed with the next name's pattern:
mkk-textfield
mkk-textarea
mkk-counter
mkk-checkbox
- ...
All of them, as you can see, starts with mkk- prefix and all of them have an input
tag inside.
I have to validate some stuff with Ajax and jQuery and add some attributes and classes at the mkk-whatever
component (not at the nested input) depending on this validation.
Example:
(Before validation)
<mkk-textfield label="Text">
<input type="text" value="" placeholder="Text" />
</mkk-textfield>
(After validation)
<mkk-textfield label="Text" class="someClass error" error-message="My custom error message">
<input type="text" value="" placeholder="Text" />
</mkk-textfield>
Is there a way to select a tag with jQuery matching a pattern like a regex? Something like jQuery selectors but for the tag:
The next example is for select all divs his name attribute starts with or contains the word value :
div[name|=”value”]
or div[name~=”value”]
But in my case I would like to do something like mkk.*
which selects all tags matching the regex.
The point is, all of them can't have id, so, I need to do that in order to use something like closest
function and, at this point, select the one with mkk- which can be a textfield a counter or whatever.
Thanks in advance.
UPDATE for a complete example. I have a form with three web components:
<mkk-textfield label="Text">
<input type="text" value="" placeholder="Text" />
</mkk-textfield>
<mkk-datepicker label="MyDate">
<input type="date" value="" placeholder="Text" />
</mkk-textfield>
<mkk-radio label="MyRadio">
<input type="radio" value="" />
</mkk-textfield>
All this web-components 'explode' in the DOM with divs and labels inside, for example, the textfield is:
<mm-textfield label="Name" class="hydrated">
<label>Name</label>
<div class="input-content">
<input id="name" type="text" value="" placeholder="Enter your name" name="name">
</div><
/mm-textfield>
When submit (validate ajax call) is done I receive in my jQuery function all the form fields and a message, so, the addError function is executed once per form field:
function addError(field, message){
// Do the magic to figure out which mkk web component is the closest one
$(/*PUT HERE THIS STACKOVERFLOW SOLUTION*/).attr("error-message", message).addClass("error");
}
I could resolve it with ifs and parent().parent() dependening on the mkk-component because each one has different html nested tags, but I wrote this question in order to do it in a more elegant way.
Hope this helps to better understand the problem.