Search code examples
csscss-selectorshref

:not CSS Selector wild card to select a tags containing # in href


I am on a mission to select a tag containing # in it's href, I am trying from 1 day but unable to get the proper css class,

What I tried: a:not([href$="\\#\\"])


Solution

  • Wildcard selector is used to select multiple elements simultaneously. It selects similar type of class name or attribute and use CSS property.

    There are 3 wildcard css selectors

    1. * Used to check if the selected thing contains the word or not. It is also known as containing wildcard.

    2. ^ Wildcard to check if selected css attribute starts with the given word.

    3. $ Wildcard to check if selected css attribute ends with the given word.

    In my case:

    <!DOCTYPE html>
    <html>
        <head>
            <style> 
              
                /* Define styles */
                a:not([href*="#"]) {  /* WE USE * HERE to check if element contains */
                    background: red;
                    color: white;
                }
                h1 {
                    color:white;
                }
                body {
                    text-align:center;
                    width:60%;
                    background: black;
                }
                a {
                   color: silver;
                }
                a[href^="#"] {
                color: blue;
                }
                a[href$="#"] {
                color: green;
                }
            </style>
        </head>
        <body>
            <h1>Example containing # in url</h1>
              
            <!-- Since we have used * with #, all items with
                 # in the above code are selected -->
            <a href="/">I am not having # in my url</a><br>
            <a href="/questions/68938789/not-css-selector-wild-card-to-select-a-tags-containing-in-href#">I am a link containing # at last.</a>
            <a href="#hello"> I am link containing # at start of href</a>
            <a href="hello#hello"> I am a link containing # in middle</a>
            <a href="https://stackoverflow.com/">i am also not having # in my url like first link</a>
        </body>
    </html>

    For more see

    1. https://www.w3.org/TR/selectors-3/#selectors
    2. https://www.geeksforgeeks.org/wildcard-selectors-and-in-css-for-classes/