Tariq Husain Tariq Husain - 6 months ago 38
Javascript Question

Unable to get offset of an elemet

i am trying to get offset of some elements which is working fine for me. But the problem occurs if element id contains single quotes. It throw an error,
e.g
if the element id is whats_next its working fine.
But if id is what's_next if gave me an error.

Error: Syntax error, unrecognized expression: #What's_Next

....value:null},t.error=function(e){throw new Error("Syntax error, unrecognized exp...


also i don't have access over HTML i can not change the HTML. Do you guys have any solution for this ?

Here is my code

$('.custom-toc li a').click(function(){
var id = $(this).attr('href');
console.log(id);
console.log($(id).offset());
});


HTML of element where i am clicking

<a rel="internal" href="#What's_Next">What's Next</a>


HTML of element offset element

<span id="What's_Next"></span>
<h4 class="editable">What's Next2</h4>

Answer

You can escape ' using replace()

HTML:

    <div class="custom-toc">
   <ul>
      <li>
        <a href="#What's_Next">dddfs</a>
      </li>
   </ul>
</div>
  <span id="What's_Next">hello</span>
<h4 class="editable">What's Next2</h4>

JS :

 $('.custom-toc li a').click(function(){
  var id = $(this).attr('href').replace(/([ #;&,.+*~\':"!^$[\]()=>|\/@])/g,'\\$1');
  console.log(id);
   console.log($(id).offset());
});