0

i have this pretty simple piece of code where i get a certain id and what im trying to do is to change the element's css. the code looks like this:

<script>
 jQuery('.sitePick').click(function(event){
   var site = (event.target.href.split("#")[1]); // get the id
   console.log(site); // make sure i get the correct id
   jQuery('#' + site).css("display" , "block"); //change css
});
</script>

the log prints the correct id of the element, and when i tried t use the same id like this : docuemnt.getElementById(site).style.display = "block" it worked, but not when using jQuery. what worries me the most its that even when i passed the id as is ( jQuery("#dummySite") to jQuery it still didn't work..any idea what i'm doing wrong? thx

UPDATE

the value of site is "site_buzzy.com". I am loading jquery right at the beginning of the file, other jquery methods work.the script being loaded after the content.

19
  • 4
    What's the value of site, coz generally integers or values starting with integers are known to cause problems. Also, 1. are you loading jQuery, 2. loading the script after loading jQuery, and thirdly, 3. loading the script after the content has been loaded? Commented Jan 6, 2016 at 12:55
  • Try using jQuery('#' + site).show();. Commented Jan 6, 2016 at 12:58
  • 4
    are you sure that the DOM is loaded when jQuery('.sitePick').click(...) is called ? to do so wrap your code with $(function(){ }); Commented Jan 6, 2016 at 12:59
  • 1
    @Pamblam It wasn't Jai than suggested diff between event.target and this :) I was just making a side note btw, i din't downvoted your answer even Jai was correct, it didn't really make sense Commented Jan 6, 2016 at 13:09
  • 2
    @Pamblam the css call is not on element.target , jQuery('#' + site) is not this Commented Jan 6, 2016 at 13:24

1 Answer 1

2

You need to escape dot(s) in some way to use site string as jQuery selector.

var site = (event.target.href.split("#")[1]).replace(/\./g, "\\.");

Now this could be simplified to:

var site = event.target.hash.replace(/\./, "\\."); // get the id
jQuery(site).show();

jQuery('.sitePick').click(function(event) {
  var site = event.target.hash.replace(/\./, "\\."); // get the id
  jQuery(site).show(); //change css
});
.hidden {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a class="sitePick" href="#site_buzzy.com">Site Pick</a>
<br />
<div id="site_buzzy.com" class="hidden">The DIV #site_buzzy.com</div>

Sign up to request clarification or add additional context in comments.

1 Comment

@Ianis No, you want as IDstring: #site_buzzy\.com

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.