nohope4you nohope4you - 5 months ago 15
jQuery Question

How to pass total number of classes preceding an element?

Here is what I'm currently doing:

<script>
function Answered(str) {
var script = document.getElementsByClassName('Answered')[str];
if(script!==null) {script.setAttribute("style", "");}
}
</script>

<span class=Answered style="background-color: #FFBED1">Is the sky blue?</span><br>
<select name="SkyBlue" onchange="Answered(0)">
<option value="">Please Select</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select><br>
<br>

<span class=Answered style="background-color: #FFBED1">How old are you?</span><br>
<input name=Age onchange="Answered(1)"><br>
<br>

<span class=Answered style="background-color: #FFBED1">Is grass green?</span><br>
<select name="GrassGreen" onchange="Answered(2)">
<option value="">Please Select</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
</select><br>


I would like to replace "Answered(0)", "Answered(1)", "Answered(2)" with something like "Answered(classes == 'Answered' preceding this element)" so as elements get moved around or inserted, the numbering doesn't have to be redone.

Jai Jai
Answer

Instead pass this:

Answered(this)

and in the script:

function Answered(el) {
   var isSpan = el.previousElementSibling;
   if(el.value!=="") {
      while(isSpan){
        if(isSpan.tagName.toLowerCase() === 'span'){
          isSpan.setAttribute("style", "");
          break;
        }
      }
   }
}