0

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?

4

1 回答 1

1

回覆:

如何使用document.querySelector选择第一个元素?

这很容易,因为document.querySelector总是只返回第一个匹配元素(如果有的话)。

你只会使用:

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

或者,如果您想更加确定:

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

在这种情况下,jQuery 选择器是相同的:

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

参考:

于 2013-10-01T03:46:54.540 回答