I need to add some CSS class based on some condition using JavaScript but facing issue in case my string contains a forward slash ( /
). This is what my use case is
<div id="div_product-size-icon-121NM/L" class="disabled"></div>
<script>
var newProductCode = '121NM/L';
if( newProductCode.contains('/') ){
newProductCode = newProductCode.replace('/','/\//');
$('#'+'div_product-size-icon-'+newProductCode).addClass('active');
}
</script>
I have even tried newProductCode.replace('/','/\\');
but while running code, I am facing following error
JavaScript error: SyntaxError: unterminated string literal
I can not change HTML along with product code; the option for me is to change it in JS.
Here is a working js example: JS code
I have first replaced the if statement with indexOf()
and changed the .replace
function as .replace('/', '\\\\/');
var newProductCode = '121NM/L'; if (newProductCode.indexOf('/') > 0) { alert('Once you click OK, the text will disappear!!'); newProductCode = newProductCode.replace('/', '\\\\/'); $('#' + 'div_product-size-icon-' + newProductCode).addClass('active'); }
div.active { display: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="div_product-size-icon-121NM/L" class="disabled">Some text here</div>
@Pugazh probably has the correct way of doing it, but you could just isolate the string
in "
by searching using an attribute
in jQuery. Here's a link to the API documentation. It avoids having to do the replace altogether. It's a hacky way of doing it.
var newProductCode = '121NM/L';
$('[id="div_product-size-icon-'+newProductCode+'"]').addClass('active');
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.