Ad

Selecting/checking The First Checkbox In A Td Class?

I'm currently trying to figure out a way to select the first checkbox (I'm not exactly sure if it's technically a radio button) that has the following HTML on a page (http://www.swagbucks.com/polls):

<td class="pollCheckbox"></td>

I have been using the following code in an attempt to select the first checkbox of the 4 that are on the page:

// ==UserScript==
// @name         SBPollSelectv2
// @version      1.0
// @description  Demonstration script to change form values
// @include      *
// @grant        none
// ==/UserScript==

var tds = document.getElementsByTagName("td");
for (var i = 0; i<tds.length; i++) {

  // If it currently has the pollCheckbox class
  if (tds[i].className == "pollCheckbox") {
    // Select first button
    document.getElementsByClassName("pollCheckbox")[0].checked = true;
  }
}

I believe that the final line of code is where the flaw lies. I can select all the TD elements by tag, and then try to sort by class. I then need to select the first checkbox with the given class. Unfortunately, my code doesn't work. I need to figure out how to select the first item with the class name and then select that checkbox. Any and all help would be awesome.

Ad

Answer

The element td is just a table cell. The checked circle appears by adding class "pollAnswerSelected" to element td with class "indivAnswerWrap". You can use the below code to check the first box. To uncheck it, just remove the class "pollAnswerSelected".

document.getElementsByClassName("indivAnswerWrap ")[0].classList.add("pollAnswerSelected")
Ad
source: stackoverflow.com
Ad