tags:

views:

35

answers:

1

If I have a certain code, How do I traverse or get to the button(i.e type == INPUT) in JavaScript.

<td> <div>
    <script></script>
    <script></script>
    <script></script>

       <input type="button"....../>
</div></td> 

I tried doing:

var cell = row.cells[0];
if (cell) {
var btn1 = cell.firstChild;
alert(btn.tagName.toUpperCase());

this resulted "DIV", and

var cell = row.cells[0];
if (cell) {
var btn = btn1.firstChild;
alert(btn.tagName.toUpperCase());

this resulted "SCRIPT"

But doing same (i.e firstChild ) , I could not succeed.

Any help is appreciated. Thanks

A: 

Give your input a name and id attribute, then you could simply do

var btn = document.getElementById("buttons_id");

..otherwise you will need a recursive function to "walk" the DOM sub-tree to find the button.

An alternative would be to use a framework such as Prototype or jQuery, which would let you simply do:

var cell = row.cells[0];
if (cell) {
  var btn = $(":button",cell); //jQuery
  $(cell).getElementsBySelector("input[type="button"]); //Prototype
}

Note that I'm not 100% precent familiar with selection in Prototype.js - the above may work, but there's probably a more concise way to do it.

FYI, here's the recursive method I was talking about before...

function findBtn(elm){
  if (elm && elm.tagName && elm.tagName.toUpperCase() == "INPUT" &&
      elm.getAttribute && elm.getAttribute("TYPE").toUpperCase() == "BUTTON") {
    return elm; //Found!
  }
  for (var i=0; i<elm.childNodes.length; i++) {
     var b = findBtn(elm.childNodes[0]);
     if (b) return b; //one of the recursive calls found it
     //else keep looping
  }
}
var btn = findBtn(row.cells[0]);
Graza
buttons get created on the fly and ids are assigned automatically
I've added a recursive method - unless you use a framework, this is your best bet.
Graza