最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Converting all text in specific element to uppercase? - Stack Overflow

programmeradmin0浏览0评论

I am trying to convert all table header text to uppercase but not successful.

<table>
<tr>
<th>product name</th>
<th>product id</th>
....

My script is as follow:

<script>
var x = document.getElementByTagName('th').innerHTML;
document.write(x.toUpperCase());
</script>

Please help....I am learning JS and almost frustrated by this simple thing.

I am trying to convert all table header text to uppercase but not successful.

<table>
<tr>
<th>product name</th>
<th>product id</th>
....

My script is as follow:

<script>
var x = document.getElementByTagName('th').innerHTML;
document.write(x.toUpperCase());
</script>

Please help....I am learning JS and almost frustrated by this simple thing.

Share Improve this question edited May 24, 2013 at 22:21 georg 215k56 gold badges322 silver badges399 bronze badges asked May 24, 2013 at 22:12 hanjayahanjaya 11 silver badge4 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

I would consider using CSS for this instead of javascript.

th {
  text-transform: uppercase;
}

If this is just for presentation, you'd probably be better of just using CSS:

th {
  text-transform: uppercase;
}

But if you really need to do it in JS:

var headers = document.getElementsByTagName("th");
for (var i = 0; i < headers.length; i++) {
  var header = headers[i];
  header.innerHTML = header.innerHTML.toUpperCase();
}

The problem with your code is that the method getElementByTagName does not exist. You have to fetch all of the s, cycle through them and apply it to each one.

jsFiddle Demo

As Brandon points out, you should really do this with css. However, if you wanted a js example of how to do it:

var headers = document.getElementsByTagName('th');
for( var i = 0, len = headers.length; i < len; i++ ){
 headers[i].innerHTML = headers[i].innerHTML.toUpperCase();
}
发布评论

评论列表(0)

  1. 暂无评论