I have a calender type deal that I am trying to create and I am hung up on selecting and changing several <td>
elements in one go. I plan on using a for loop to accomplish this by traversing each node and modifying its text each iteration, but I am confused on how to actually access the text. If I have, in my external:
var daysInWeek = document.getElementsByTagName("td");
And in HTML:
<tr><td id="w1_mo">w1d1</td>
<td id="w1_tu">w1d2</td>
<td id="w1_we">w1d3</td>
<td id="w1_th">w1d4</td>
<td id="w1_fr">w1d5</td>
<td id="w1_sa">w1d6</td>
<td id="w1_su">w1d7</td></tr>
Five of them
How do I go about accessing the node next to the previous and changing its text?
It would appear that the dot operator does not give me the same options as .getElementById()
does. I understand there is also .item(index: int)
as well but it would appear I get the same options as elements by tag name.
Suggestions for a noob Javascripter?
getElementsByTagName
gives you a NodeList
with matching elements in it. You access the elements using either A) brackets notation: [n]
where n
is 0 <= n < list.length
, or B) Using .item(n)
(same range for n
).
So for instance, this accesses the first td
in the document:
var daysInWeek = document.getElementsByTagName("td");
var firstTdInDocument = daysInWeek[0];
That's an HTMLElement
object. To access its contents, you use:
...its childNodes
property to access all of its direct child nodes. childNodes
is a NodeList
containing Text
and Element
nodes (and possibly Comment
nodes)
...its children
property if you want a subset of childNodes
that only includes Element
instances
...its textContent
(standard) or innerText
(IE-specific) property to access its contents as straight text (markup is stripped out)
...its innerHTML
property to access its contents as HTML
...its nextSibling
or nextElementSibling
properties if you want to access the Node
(nextSibling
) or Element
(nextElementSibling
) that follows it in the tree (in the case of td
elements, that's usually another td
element or null
)
...its previousSibling
or previousElementSibling
to go the other way
So for instance, to set the HTML of the first td
in the document:
document.getElementsByTagName("td")[0].innerHTML = "I'm the first <code>td</code> element";
Note that you're not limited to crude things like getElementsByTagName
anymore; you can use querySelector
and querySelectorAll
to get the first matching element or a list of matching elements, respectively, for any arbitrary CSS expression. This is supported on document
and also on Element
instances on all modern browsers, and also IE8+.
So for instance, another way to update the text of the first td
in the document is:
document.querySelector("td").innerHTML = "I'm the first <code>td</code> element";
Or
document.querySelectorAll("td")[0].innerHTML = "I'm the first <code>td</code> element";