1

I am trying to modify the css of a class depending on the URL. Here is the currently non-working code:

JS:

<script>
//<![CDATA[ 
if (location.pathname == "/SearchResults.asp" 
|| location.pathname.indexOf("-s/") != -1 
|| location.pathname.indexOf("_s/") != -1) 
$('.colors_productname span').css("background-color", "#F7F7F7");
//]]> 
</script>

HTML:

<div>
    <a href="#" class=
    "productnamecolor colors_productname" title="Cracked Pepper"><span itemprop=
    'name'>Cracked Pepper</span></a><br />
    <div>
    <div>
      <b><font class="pricecolor colors_productprice"><span class=
      "PageText_L483n">$11.00</span></font></b>
    </div>
    <img src="#" /></div>
</div> 

Notes:

  1. I can't change the HTML, it is automatically generated

  2. The URL of the HTML includes "/Meats-s/", so it should be targeted by the second if conditional.

  3. I can edit it with the same css selector (.colors_productname span) in a normal .css file, but this does not work.

3
  • Did you put your JavaScript in a tag at the bottom of your body below your jQuery? The <font> tag is not supported in HTML5. Commented Jul 11, 2013 at 1:03
  • @PHPglue: what does "not supported in HTML5" mean? "red".fontcolor("red") still shows as red when i use an HTML5 doctype, despite the invalid color spec and terrible semantics... i thought all non-spec'd tags mean "SPAN" in HTML5. Commented Jul 11, 2013 at 2:38
  • See: w3schools.com/tags/tag_font.asp Commented Jul 11, 2013 at 21:56

1 Answer 1

6

Encase your code in DOM Ready handler

$(function() {
    // Your code
});

Encasing your code in the above handler will make sure you code runs only after the elements are available in the DOM.

And it is always faster to use === instead of == .

Also you seem to be using the window.location multiple times. Consider caching it.

$(function() {
   var loc = location.pathname;
   if (loc === "/SearchResults.asp" || loc.indexOf("-s/") !== -1
                                    || loc.indexOf("_s/") !== -1
   $('.colors_productname span').css("background-color", "#F7F7F7");
});
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant, this works. I knew it had to be something simple. Thanks!

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.