Css Selector

    Css Selector in Selenium



    I. Css Selector in Selenium

    Class : In CSS we mention class using the . sign

    Html Code : <label class='expand'>css class</label>
    
    Css selector value : .expand
    Css selector value : label[class='expand']

    Id : CSS selector uses # sign with id attribute to locate the element

    Html Code : <label id='fourth'>css id</label>
    
    Css selector value : #fourth

    Tagname : Tagname is used to form the element in HTML, we can use tagname without any symbols,

    Html Code : <label id='fourth'>css id</label>
    
    Css selector value : label

    Combination : Sometimes there will scenarios where you may not able to find the element uniquely, in those cases we have to take the references of its parent element properties

    Html Code : <div id='abc' class='column'>
    				      <label id='fourth' class='expand'>css id</label>
    			      </div>
    
    Css with class : .column.expand
    Css with id : .abc.fourth
    Css with tagname : div label
    Css with mix 1: div.column#fourth
    Css with mix 1: #abc label.expand

    II. The wild card in the CSS selector

    We can use wild card characters in CSS selector to find the element, ^, $, * are wild card characters present in the CSS selector in selenium

    <label name='example'>css selector</label>


    '^' means start of the string : label[name^='ex']

    '$' means the end of the string : label[name$='le']

    '*' means contain the string : label[name*='mp']


    III. CSS Selector Cheat Sheet


    SyntaxExample    Description
    .class.intro    Selects all elements with class="intro"
    #id#firstname    Selects the element with id="firstname"
    **    Selects all elements
    elementp    Selects all <p> elements
    element,elementdiv, p    Selects all <div> elements and all <p> elements
    element elementdiv p    Selects all <p> elements inside <div> elements
    element>elementdiv > p    Selects all <p> elements where the parent is a <div> element
    element+elementdiv + p    Selects all <p> elements that are placed immediately after <div> elements
    element1~element2p ~ ul    Selects every <ul> element that are preceded by a <p> element