Steven Matthews
Steven Matthews

Reputation: 11325

Selecting the innerHTML of two <td>'s inside a <tr id="blahblahblah">

Ok, so I've got an onclick event (CF-D07 is an example, these are generated programmatically based on a MySQL database):

<input type="checkbox" onclick="var nameUpdate = 'CF-D07';
datechange();" id="CF-D07">

So then, under datechange(), I have this:

function datechange() {
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject

("Microsoft.XMLHTTP");

  }

document.body.getElementsByTagName("tr").getElementsById(nameUpdate);

   // This section isn't done yet.

   // var url = "changedate.psp"
   // var params = "user=" + nameUpdate

   // xmlhttp.open("GET", url + "?" + params,false);
   // xmlhttp.send();
   // xmlDoc=xmlhttp.responseXML;

}

The important part of this is this part of the code:

document.body.getElementsByTagName("tr").getElementsById(nameUpdate);

How do I make it so that I get all of the elements with the tag, that then have the id of nameUpdate, based on the onclick event? And then after that, how do I select the innerHTML of the first two 's in the and put it into separate variables?

Upvotes: 0

Views: 421

Answers (1)

rossipedia
rossipedia

Reputation: 59397

If I'm understanding you correctly, you should never have more than one element with the same ID on any page. If you need to classify html elements, use the class attribute.

To get the inner html of elements, you can use aptly named innerHTML property of the DOM element:

function datechange(nameUpdate) {
    var xmlhttp;
    if (window.XMLHttpRequest) {
        // code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();  
    } else {
        // code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

    }

    // document.body.getElementsByTagName("tr").getElementsById(nameUpdate);
    var trs = document.getElementByClassName(nameUpdate);

    for(var i = 0, len = trs.length; i < len; ++i) {
        var html = tr.innerHTML;
        // Do what you need to with HTML
    }
}

With the above code, your original HTML snippet could look like this:

<input type="checkbox" onclick="datechange('CF-D07')">

This also assumes you'd have a tr somewhere that looks something like this:

<tr class="CF-D07">
    <td>...</td>
    <td>...</td>
</tr>

To access the <td> elements of a given <tr>, you can use the children property for all child elements, or you can use getElementsByTagName directly on the tr element:

var tr = ... // get the TR somehow
var tds = tr.getElementsByTagName('td');
var allHTML = "";
for(var i = 0, len = tds.length; i < len; ++i) {
    allHTML += tds[i].innerHTML;
}

// Do something with allHTML, which is the inner html of all tds put together

Upvotes: 1

Related Questions