Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

javascript - Changing background color of all elements with the same class

I have a link and a table row that have matching classes. When the link is clicked, I would like to change the background color of the row with the same class. For each case, there will be only one row with the same class.

Here is my current function.

   <script type="text/javascript">

function check(x) {
    elements = document.getElementsByClassName(x);
    for (var i = 0; i < elements.length; i++) {
        elements[i].bgColor="blue";
    }
}
</script>

Here is a part of the table row script:

<tr class="alt1 12">
<td width="50" height="55">
<img src="iPhone/statusicon/12.png" alt="" id="forum_statusicon_12" border="0"></td>
<td>
<div class="forumtitle">
<a class="forumtitle 12" href="forumdisplay.php?f=12" action="async" onclick="check(this.className.split(' ')[1])">News and Current Events</a></div>
</td>
<td width="25">
<div class="forumarrow"><img src="iPhone/chevron.png" alt="" border="0"></div>
</td>
</tr>

The table row has two classes, and I need the second one (the number) to be what is addressed. The current code gives the error "An invalid or illegal string was specified"

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have several errors. You mixed classes with ids and also the class property is actually className

<script type="text/javascript">

function check(x) {
    elements = document.getElementsByClassName(x);
    for (var i = 0; i < elements.length; i++) {
        elements[i].style.backgroundColor="blue";
    }
}

</script>

<a href="#" class="first" onclick="check(this.className)">change first row</a>
<a href="#" class="second" onclick="check(this.className)">change second</a>
<!--        FIX ( id -> class )                FIX ( class -> className ) -->
<table>
<tr class="first">
<td>test1</td>
</tr>


<tr class="second">
<!--FIX ( id -> class ) -->
<td>test2</td>
</tr>
</table>

Check this jsfiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...