skip to Main Content

If I want to locate only ‘grape’, what should I do? I tried using document.querySelector, but it doesn’t work. I don’t know how to locate html tags that don’t have an ID or class.

        <h2 class="fruits">
            <ul>
                <li>apple</li>
                <li>grape</li>
            </ul>
        </h2>

2

Answers


  1. document.evaluate() lets you use xpath. The xpath //*[.='grape'] should find elements with the text ‘grape’.

    This syntax is a bit ugly.

    document.evaluate('//*[.="grape"]', document).iterateNext()
    

    returns the first node matching the xpath.

    Login or Signup to reply.
  2. This can solve your problem :

    document.querySelectorAll(".fruits ul li")[1].style.color = "#009999";
    <h2 class="fruits">
         <ul>
              <li>apple</li>
              <li>grape</li>
         </ul>
    </h2>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search