1

I want to use a Greasemonkey script to click a button.

The button HTML starts like below; there are 3 buttons, corresponding to 48/50/52 respectively. The 48/50/52 are not identical, so is there some way to selectively click the button by mean of choosing the first one in the class="modeNum"?

I just want the first one to be clicked.

The button code:

<dl class="numSize">
    <dt>size:</dt>
    <dd class="modeNum">
        <a href="javascript:void(0);" rev="6" rel="3">48</a>
        <a href="javascript:void(0);" rev="10" rel="3">50</a>
        <a href="javascript:void(0);" rev="1" rel="1">52</a></dd>
        <dd class="dps">
        <a href="javascript:;">size chart</a>
    </dd>
    <dd class="clear"></dd>
</dl>

...and when the second button is clicked, the code changes to:

<dl class="numSize">
    <dt>size:</dt>
    <dd class="modeNum">
        <a href="javascript:void(0);" rev="6" rel="3">48</a>
        <a class="Active" href="javascript:void(0);" rev="10" rel="3">50</a>
        <a href="javascript:void(0);" rev="1" rel="1">52</a></dd>
        <dd class="dps">
        <a href="javascript:;">size chart</a>
    </dd>
    <dd class="clear"></dd>
</dl>


How to use document.querySelector to select the first <a> element?

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
user1663601
  • 65
  • 1
  • 6

1 Answers1

2

Re:

How to use document.querySelector to select the first element?

That's easy as document.querySelector always only returns the first matching element (if any).

You would merely use:

var firstBtn = document.querySelector ("dl.numSize > dd.modeNum > a");
if (firstBtn) {
    // DO YOUR CLICK OR WHATEVER, HERE.
}

Or, if you want to be extra sure:

var firstBtn = document.querySelector ("dl.numSize > dd.modeNum > a:first-of-type");
if (firstBtn) {
    // DO YOUR CLICK OR WHATEVER, HERE.
}

The jQuery selector is identical in this case:

var firstBtn = $("dl.numSize > dd.modeNum > a:first-of-type");
if (firstBtn.length) {
    // DO YOUR CLICK OR WHATEVER, HERE.
}

Reference:

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
  • Adams, thank you for your help. that works, and the reference is very helpful for learning this topic. Thanks again. – user1663601 Oct 14 '13 at 15:00
  • You're welcome. If this solves your problem, then [tick the check-mark next to this answer](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235). – Brock Adams Oct 14 '13 at 22:16