简体   繁体   中英

CSS Selector doesn't work as expected

I am developing a website which relies on user input to create scripts As a defense in depth solution I am adding a blacklist protection to omit all links with an external source. I tried the following code snippet but it doesn't work (my browser supports it because w3schools sample works on it) :

    [href~=//]
    {
        display: none;
    }

Try this:

a[href*="//"]{
  display:none;
}

Select all a objects whose href contains '//'

working fiddle

There's a subtle different in the selectors that you are using :

  • [attribute~="value"] - This checks for a specific word (ie wrapped in white-space or the exact string)
  • [attribute*="value"] - This checks if a given set of text is contained at all.

You'll see that the second approach works, whereas the first does not.

Additionally, you'll want to ensure that you have the specific element you are targeting and that you are wrapping your value within quotes, as seen below :

a[href*='//']{
        display: none;
}

Example

 a[href*='//'] { display: none; } /* Added to demonstrate selector differences */ a[href~='//'] { color: green; display: block; } 
 <h4>[href*="value"] Examples</h4> <a href='http://www.google.com'>Hidden</a> <a href='stackoverflow.com'>Shown</a> <a href='Check // this out'>Green</a> <h4>[href~="value"] Examples</h4> <a href='a//'>Hidden (since not whole "word")</a> <a href='//'>Shown (as exact)</a> <a href='//a'>Hidden (since not whole "word")</a> 

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