How To Match Complex Element IDs In jQuery
erics, Posted July 22nd, 2021 at 1:36:59pm
PROBLEM: An element ID that looked like this would fail to match:
service = east
node = db1-demo.thedomain.com
1 2 |
<div style="width: 50px; height: 50px; background: #00aa00; color: #000;" id="Div-node-notes-east-db1-demo.thedomain.com">Content to hide and show here</div> <a href="#" onclick="jQuery('#Div-node-notes-'+service+'-'+node.toggle();return false;">Toggle Div</a> |
SOLUTION: Rig any special characters in the complex hostname (:.[],-@) with a backslash in front of them to ensure proper matching:
1 2 3 4 5 6 7 8 |
<script> var G={}; G.cleanid = function(myid) { return myid.replace( /(:|\.|\[|\]|,|=|@)/g, "\\$1" ); } </script> <div style="width: 50px; height: 50px; background: #00aa00; color: #000;" id="Div-node-notes-east-db1-demo.thedomain.com">Content to hide and show here</div> <a href="#" onclick="jQuery('#Div-node-notes-'+service+'-'+G.cleanid(node).toggle();return false;">Toggle Div</a> |
Leave Your Comment
All fields marked with "*" are required.