How to get a div having $ as first character

Suppose i have a div with ID '$abc'. How do i select it using jQuery? Below is the sample code snippet.

function abc(){
	$('#$abc').text('abc')
}
abc();
<script
  src="https://code.jquery.com/jquery-3.1.1.slim.min.js"
  integrity="sha256-/SIrNqv8h6QGKDuNoLGA4iret+kyesCkHGzVUUV0shc="
  crossorigin="anonymous"></script>
  
  <div id="$abc"></div>

When i try running this i get an error in console like this-

Uncaught Error: Syntax error, unrecognized expression: #$abc
at Function.ga.error (jquery-3.1.1.slim.min.js:2)
at ga.tokenize (jquery-3.1.1.slim.min.js:2)
at ga.select (jquery-3.1.1.slim.min.js:2)
at Function.ga [as find] (jquery-3.1.1.slim.min.js:2)
at r.fn.init.find (jquery-3.1.1.slim.min.js:2)
at r.fn.init (jquery-3.1.1.slim.min.js:2)
at r (jquery-3.1.1.slim.min.js:2)
at abc (fiddle.jshell.net/:46)
at window.onload (fiddle.jshell.net/:48)

Answers 1

  • You can do it like below:-

    function abc(){
     $('div[id="$abc"]').text('abc');
    }
    abc();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha256-/SIrNqv8h6QGKDuNoLGA4iret+kyesCkHGzVUUV0shc=" crossorigin="anonymous"></script>
      
    <div id="$abc"></div>

    Note:- this is called [attribute|=value] selectors

    Reference:- All possible seletors


Related Articles