简体   繁体   中英

jQuery not changing CSS even though element found in array?

Apologies in advance if this question is unclear; I'm pretty new.

I am working on a Chrome extension to change the color of most viewed headlines on www.nytimes.com. My issue is that I can't get jQuery to reliably override the CSS on a page.

I am using a function to search all the anchors on the page, comparing the text of those anchors to an array of titles, and modifying the CSS if the text matches one of the titles. Here's what I have:

$("a").each(function() {
    $this = $(this);
    if ($.inArray($this.text(), titles) !== -1) {
      console.log("found title");
      $this.css('color', color);
    }
  });

The console.log statement is for testing, and it is indeed showing me that I'm finding 8 matches on my page at the moment. However, only four of the matches are getting the CSS color applied. The four titles that get changed are all in the "most emailed" section of the page. The corresponding titles in the main body of the page do not get changed, even though the text of the headlines is identical.

What am I missing?

try the working DEMO here ,

$this.css('color', 'red');

and use .trim() for exact string comparisons,

$this.text().trim()

try replacing this line

$this.css('color', color);

to

$this.css({color:'#006600'});

Check your .css file. If that file contains something like follows for your text:

someSelector {
 ... 
  ...
 color: "somecolor !important ";
 ... 

}

Then jQuery can't override it via code. Please modify your css file first and then try setting it with code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM