Dilkush Dilkush - 7 months ago 8
Javascript Question

trying to find if certain characters are present in an id

<span class="help-block" style="color:red;text-align:left;" id="1012Error">Error Block</span>
<span class="help-block" style="color:red;text-align:left;" id="1013">Clear</span>
<span class="help-block" style="color:red;text-align:left;" id="1012Error">Error Block</span>
<span class="help-block" style="color:red;text-align:left;" id="1012">Clear</span>


am trying to achieve something like this

if(id contains "error")
{
$(this).html("");
}


can someone guide me how to get this

Answer

jQuery features selectors that can be used to target specific elements based on their attributes. In this case, there are two that you could use in this scenario.

The Ends With Selector $=

You could find any elements having attributes that end-with a specific phrase using $= attribute selector through the following syntax:

// This will empty the HTML for any element that has an ID that ends with "Error" 
$('[id$="Error"]').html('');

The Contains Selector *=

Similarly, the *= attribute selector will find any elements that have a certain attribute that "contains" a specific value:

$('[id*="Error"]').html('');

Handle Multiple Operations via each()

If you needed to perform multiple operations for your elements, you could use the each() function to iterate through them and handle your operations :

// Find each element that ends with "Error"...
$('[id*="Error"]').each(function(){
     // And clear it out
     $(this).html('');
     // Then do something else here
});