2

I have DIV and inside div it has table. I want to change the one of the column value of table using java script. I can do it by getting the element id of column, but there is no any id assigned to any table's column. Below is the example.

<div id="usersec">
<TABLE style="TEXT-ALIGN: center; WIDTH: 279px; HEIGHT: 70px">
<TBODY>
<TR>
<TD style="FONT-FAMILY: Verdana" vAlign=center align=middle>Talk to me </TD></TR></TBODY></TABLE>
</div>

Is it possible to change the "Talk to me" text using javascript?

2
  • Do you only ever have the one <td> in the table? Or are you asking us how to find a specific <td> without an id attribute, eg based on its content? Commented Mar 28, 2013 at 14:53
  • Are you happy to use a lib, such as jQuery? Commented Mar 28, 2013 at 14:55

3 Answers 3

3

If your userbase is IE8+, you can safely use querySelector:

var container = document.getElementById('usersec');
var td = container.querySelector('tr:first-child > td');
if(td){
  td.innerHTML = "New Text!";
}

Here's a JSFIDDLE: http://jsfiddle.net/rgthree/YkhwE/

querySelector (or querySelectorAll) allow you to target elements in the DOM via CSS syntax, which is very useful. It's very well supported, in every current and previous browser. (via Can I Use)

Sign up to request clarification or add additional context in comments.

Comments

2

Yes, you need to get the element and then set a new value to element.innerHTML. It's easiest if you give an id to the element that you want to change but you don't need to

jsFiddle

<script type="text/javascript">
    var usersec = document.getElementById('usersec');
    var td = usersec.getElementsByTagName('td')[0];
    td.innerHTML = 'New value';
</script>

Comments

0

You can assign an id to the TD, and use that;

<div id="usersec">
<TABLE style="TEXT-ALIGN: center; WIDTH: 279px; HEIGHT: 70px">
<TBODY>
<TR>
<TD style="FONT-FAMILY: Verdana" vAlign=center align=middle id="cellToChange">Talk to me</TD>
</TR></TBODY></TABLE>
</div>

<script type="text/javascript">
document.getElementById("cellToChange").innerText = "Go on, talk to me please!";
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.