user3293200
user3293200

Reputation: 1

On a target page with multiple id's, script is acting only on the first one

I'm filling in a text box using Greasemonkey. It's working, but the page has more than one <input> with the same id, and GM is only filling in the first one.

The page's HTML (repeated 3 times):

<input type="text" id="se" value="" class="form">


My GM Code:

document.getElementById("se").value = "na";


How can I set the 2nd or 3rd <input> too?

Upvotes: 0

Views: 62

Answers (2)

Alex W
Alex W

Reputation: 38243

You could iterate the input elements on the page, looking for a specific id value:

var elements = document.getElementsByTagName('input');

for(var i = 0; i < elements.length; i++)
{
    if(elements[i].id === "se")
    {
        elements[i].value = "na";
    }
}

fiddle

Upvotes: 0

Brock Adams
Brock Adams

Reputation: 93533

Yeah, pages with malformed HTML are a right pain. Fortunately, querySelectorAll() usually works as one would hope on such pages. (Alas, libraries, even jQuery, usually don't handle the malformed pages as well.)

In this case, the following code should work for you:

var badInputs = document.querySelectorAll ("#se");

for (var J = badInputs.length - 1;  J >= 0;  --J) {
    var tInput      = badInputs[J];
    tInput.value    = "na";
}


You can see the code in action at jsFiddle.

Upvotes: 2

Related Questions