473,788 Members | 3,057 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How do I add a class to an <a> tag on a onclick() event using Javascipt/DOM?

SM
Hello,
I have an <ul>, and when i click on a item i want to add a class to
that item. The class itself will change some display properties, using
CSS. See code below.
But, whenever i click on a item, the CSS properties, always applies to
the last item in the list.

How can i achieve this using JavaScript and the DOM?
-------------------
var ul = document.create Element('ul');
ul.className = 'cdTrack';

....
for(var j=0; j<titleTrackEle ms.length; j++)
{
li = document.create Element('li');

liValue =
document.create TextNode(titleT rackElems.item( j).childNodes[0].nodeValue);
li.appendChild( liValue);

a = document.create Element('a');
a.setAttribute( 'href', '#');
aValue = document.create TextNode(...);
a.appendChild(a Value);
a.onclick = function () { a.className='he re'; };

li.appendChild( a);
}

ul.appendChild( li);
....
-------------------

Thanks
Marco

May 23 '07 #1
5 2726
SM said the following on 5/23/2007 1:57 PM:
Hello,
I have an <ul>, and when i click on a item i want to add a class to
that item. The class itself will change some display properties, using
CSS. See code below.
But, whenever i click on a item, the CSS properties, always applies to
the last item in the list.

How can i achieve this using JavaScript and the DOM?
-------------------
var ul = document.create Element('ul');
ul.className = 'cdTrack';

...
for(var j=0; j<titleTrackEle ms.length; j++)
{
li = document.create Element('li');

liValue =
document.create TextNode(titleT rackElems.item( j).childNodes[0].nodeValue);
li.appendChild( liValue);

a = document.create Element('a');
a.setAttribute( 'href', '#');
aValue = document.create TextNode(...);
a.appendChild(a Value);
a.onclick = function () { a.className='he re'; };
this.className;

And then ask about "this" and the issue that will arise from it.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javas cript FAQ - http://jibbering.com/faq/index.html
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
May 23 '07 #2
SM
On May 23, 5:26 pm, Randy Webb <HikksNotAtH... @aol.comwrote:
SM said the following on 5/23/2007 1:57 PM:
Hello,
I have an <ul>, and when i click on a item i want to add a class to
that item. The class itself will change some display properties, using
CSS. See code below.
But, whenever i click on a item, the CSS properties, always applies to
the last item in the list.
How can i achieve this using JavaScript and the DOM?
-------------------
var ul = document.create Element('ul');
ul.className = 'cdTrack';
...
for(var j=0; j<titleTrackEle ms.length; j++)
{
li = document.create Element('li');
liValue =
document.create TextNode(titleT rackElems.item( j).childNodes[0].nodeValue);
li.appendChild( liValue);
a = document.create Element('a');
a.setAttribute( 'href', '#');
aValue = document.create TextNode(...);
a.appendChild(a Value);
a.onclick = function () { a.className='he re'; };

this.className;

And then ask about "this" and the issue that will arise from it.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javas cript FAQ -http://jibbering.com/faq/index.html
Javascript Best Practices -http://www.JavascriptT oolbox.com/bestpractices/
Hey Randy,
I've try it, but doesn't seem to work?
What is the issue that will arise from it?

Thanks
Marco

May 25 '07 #3
SM
On May 25, 7:13 pm, SM <servandomont.. .@gmail.comwrot e:
On May 23, 5:26 pm, Randy Webb <HikksNotAtH... @aol.comwrote:
SM said the following on 5/23/2007 1:57 PM:
Hello,
I have an <ul>, and when i click on a item i want to add a class to
that item. The class itself will change some display properties, using
CSS. See code below.
But, whenever i click on a item, the CSS properties, always applies to
the last item in the list.
How can i achieve this using JavaScript and the DOM?
-------------------
var ul = document.create Element('ul');
ul.className = 'cdTrack';
...
for(var j=0; j<titleTrackEle ms.length; j++)
{
li = document.create Element('li');
liValue =
document.create TextNode(titleT rackElems.item( j).childNodes[0].nodeValue);
li.appendChild( liValue);
a = document.create Element('a');
a.setAttribute( 'href', '#');
aValue = document.create TextNode(...);
a.appendChild(a Value);
a.onclick = function () { a.className='he re'; };
this.className;
And then ask about "this" and the issue that will arise from it.
--
Randy
Chance Favors The Prepared Mind
comp.lang.javas cript FAQ -http://jibbering.com/faq/index.html
Javascript Best Practices -http://www.JavascriptT oolbox.com/bestpractices/

Hey Randy,
I've try it, but doesn't seem to work?
What is the issue that will arise from it?

Thanks
Marco
Sorry, just try it again, and it does work! But, whenever i click on a
link the 'here' class applies correctly but if i click again on
another link the class also applies (wich makes sense)

Im trying to highlight only the one selected. Is that the issue you
were talking about?

Thanks
Marco

May 25 '07 #4
On May 26, 9:26 am, SM <servandomont.. .@gmail.comwrot e:
On May 25, 7:13 pm, SM <servandomont.. .@gmail.comwrot e:
On May 23, 5:26 pm, Randy Webb <HikksNotAtH... @aol.comwrote:
SM said the following on 5/23/2007 1:57 PM:
Hello,
I have an <ul>, and when i click on a item i want to add a class to
that item. The class itself will change some display properties, using
CSS. See code below.
But, whenever i click on a item, the CSS properties, always applies to
the last item in the list.
How can i achieve this using JavaScript and the DOM?
-------------------
var ul = document.create Element('ul');
ul.className = 'cdTrack';
...
for(var j=0; j<titleTrackEle ms.length; j++)
{
li = document.create Element('li');
liValue =
document.create TextNode(titleT rackElems.item( j).childNodes[0].nodeValue);
li.appendChild( liValue);
a = document.create Element('a');
a.setAttribute( 'href', '#');
aValue = document.create TextNode(...);
a.appendChild(a Value);
a.onclick = function () { a.className='he re'; };
this.className;
And then ask about "this" and the issue that will arise from it.
--
Randy
Chance Favors The Prepared Mind
comp.lang.javas cript FAQ -http://jibbering.com/faq/index.html
Javascript Best Practices -http://www.JavascriptT oolbox.com/bestpractices/
Hey Randy,
I've try it, but doesn't seem to work?
What is the issue that will arise from it?
Thanks
Marco

Sorry, just try it again, and it does work! But, whenever i click on a
link the 'here' class applies correctly but if i click again on
another link the class also applies (wich makes sense)

Im trying to highlight only the one selected. Is that the issue you
were talking about?
I don't think so - I think Randy was expecting you to discover more
about a function's this keyword.

Anyhow, what you want to do is to remove the classname from the last
link and add it to the current link. You can use a global variable to
do that, or you can remove the class from all the links and add it to
just the last one. Below is some stuff that does that, doing it
properly likely takes more code than you thought. Tested in Safari
and Firefox:
// Modified trim from clj FAQ to also remove multiple spaces
String.prototyp e.trim = function() {
return this.replace(/^\s+|\s+$/g,'').replace(/\s+/,' ');
}

// Utility function namespace
var xU = xU || {};

// Add a className
xU.addClass = function (el, className){
var re = new RegExp('(^|\\s) '+className+'(\ \s|$)');
if (!re.test(el.cl assName)) {
el.className += (' ' + className).trim ();
}
}

// Remove a className
xU.removeClass = function (el, className){
var re = new RegExp('(^|\\s) '+className+'(\ \s|$)');
el.className = (el.className.r eplace(re, ' ')).trim();
}

// See if el has className
xU.hasClassname = function (el, className){
var re = new RegExp('(^|\\s) '+className+'(\ \s|$)');
return (re.test(el.cla ssName));
}

// Return an element by tagName. If el's tag name isn't
// tagName, search up DOM tree. Return the first match
// or null if none found.
xU.upToTagname = function (el, tagName){
while (el.parentNode && el.tagName.toLo werCase() != tagName) {
el = el.parentNode;
}
return (el.tagName &&
el.tagName.toLo werCase() == tagName)? el : null;
}

// Highlight the last A element that was clicked on
function highLightLastLi nk(e){
var e = e || window.event;
var tgt = e.target || e.srcElement;

// If can't find A, or already has className, return
if ( !(tgt = xU.upToTagname( tgt, 'a')) ||
xU.hasClassname (tgt, 'red')) {
return;
}

// Remove className from any A that has it
var aElements = document.getEle mentsByTagName( 'a');
var i = aElements.lengt h;
while (i--){
xU.removeClass( aElements[i], 'red')
}

// Add className
xU.addClass(tgt , 'red');
}

window.onload = function(){
document.body.o nclick = highLightLastLi nk;
}
--
Rob

May 26 '07 #5
SM
On May 25, 10:55 pm, RobG <r...@iinet.net .auwrote:
On May 26, 9:26 am, SM <servandomont.. .@gmail.comwrot e:
On May 25, 7:13 pm, SM <servandomont.. .@gmail.comwrot e:
On May 23, 5:26 pm, Randy Webb <HikksNotAtH... @aol.comwrote:
SM said the following on 5/23/2007 1:57 PM:
Hello,
I have an <ul>, and when i click on a item i want to add a class to
that item. The class itself will change some display properties, using
CSS. See code below.
But, whenever i click on a item, the CSS properties, always applies to
the last item in the list.
How can i achieve this using JavaScript and the DOM?
-------------------
var ul = document.create Element('ul');
ul.className = 'cdTrack';
...
for(var j=0; j<titleTrackEle ms.length; j++)
{
li = document.create Element('li');
liValue =
document.create TextNode(titleT rackElems.item( j).childNodes[0].nodeValue);
li.appendChild( liValue);
a = document.create Element('a');
a.setAttribute( 'href', '#');
aValue = document.create TextNode(...);
a.appendChild(a Value);
a.onclick = function () { a.className='he re'; };
this.className;
And then ask about "this" and the issue that will arise from it.
--
Randy
Chance Favors The Prepared Mind
comp.lang.javas cript FAQ -http://jibbering.com/faq/index.html
Javascript Best Practices -http://www.JavascriptT oolbox.com/bestpractices/
Hey Randy,
I've try it, but doesn't seem to work?
What is the issue that will arise from it?
Thanks
Marco
Sorry, just try it again, and it does work! But, whenever i click on a
link the 'here' class applies correctly but if i click again on
another link the class also applies (wich makes sense)
Im trying to highlight only the one selected. Is that the issue you
were talking about?

I don't think so - I think Randy was expecting you to discover more
about a function's this keyword.

Anyhow, what you want to do is to remove the classname from the last
link and add it to the current link. You can use a global variable to
do that, or you can remove the class from all the links and add it to
just the last one. Below is some stuff that does that, doing it
properly likely takes more code than you thought. Tested in Safari
and Firefox:

// Modified trim from clj FAQ to also remove multiple spaces
String.prototyp e.trim = function() {
return this.replace(/^\s+|\s+$/g,'').replace(/\s+/,' ');

}

// Utility function namespace
var xU = xU || {};

// Add a className
xU.addClass = function (el, className){
var re = new RegExp('(^|\\s) '+className+'(\ \s|$)');
if (!re.test(el.cl assName)) {
el.className += (' ' + className).trim ();
}

}

// Remove a className
xU.removeClass = function (el, className){
var re = new RegExp('(^|\\s) '+className+'(\ \s|$)');
el.className = (el.className.r eplace(re, ' ')).trim();

}

// See if el has className
xU.hasClassname = function (el, className){
var re = new RegExp('(^|\\s) '+className+'(\ \s|$)');
return (re.test(el.cla ssName));

}

// Return an element by tagName. If el's tag name isn't
// tagName, search up DOM tree. Return the first match
// or null if none found.
xU.upToTagname = function (el, tagName){
while (el.parentNode && el.tagName.toLo werCase() != tagName) {
el = el.parentNode;
}
return (el.tagName &&
el.tagName.toLo werCase() == tagName)? el : null;

}

// Highlight the last A element that was clicked on
function highLightLastLi nk(e){
var e = e || window.event;
var tgt = e.target || e.srcElement;

// If can't find A, or already has className, return
if ( !(tgt = xU.upToTagname( tgt, 'a')) ||
xU.hasClassname (tgt, 'red')) {
return;
}

// Remove className from any A that has it
var aElements = document.getEle mentsByTagName( 'a');
var i = aElements.lengt h;
while (i--){
xU.removeClass( aElements[i], 'red')
}

// Add className
xU.addClass(tgt , 'red');

}

window.onload = function(){
document.body.o nclick = highLightLastLi nk;

}

--
Rob
Wow! ok, wasn't expecting that much code to highlight a simple text.
Thanks anyways
Marco

May 26 '07 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
1036
by: Raghul | last post by:
Hi friends, I am creating a jabber client and a separate class for dialog is created,So when the roster name is clicked this dialog open and can continue chat.What I need is I am calling the same class when reciving the message so that the application goes not responding.People told me to use threading for this. Can any one help me in calling the same dialog class using threading...
2
10569
by: Donald Firesmith | last post by:
I am having trouble having Google Adsense code stored in XSL converted properly into HTML. The <> unfortunately become &lt; and &gt; and then no longer work. XSL code is: <script type="text/javascript"> <!]> </script> <script type="text/javascript"
0
1158
by: Jonah Olsson | last post by:
Dear Sirs, I'm looking for a way to define a class using an XML file. Since I'm building a Web Service to be used by several customers I want to be able to easily change the class below without having to change the actual code. This class is also used in the communication with the customer's SQL server. Thanks for any kind of help. Regards,
2
2154
by: | last post by:
Today I learned that creating cookies inside of a custom class in ASP.NET 2.0 requires that you prefix it with HttpContext.Current..., e.g. : HttpContext.Current.Response.Cookies.Add("myNewCookie"); I am wondering if there are any landmines that I should know about, or if this will work pretty much as I am expecting a cookie should.
0
948
by: Shrage H. Smilowitz | last post by:
I have posted this question in the vision forum and got no response, so maybe one of the vb developers here can aswere me. In VB.net classes can have Properties (Attributes in UML), Functions (Operations in UML) How do i show a Class Event in a UML Static structure. Also, it seems like interfaces in a static structure does not support Operations waht do i do if want to represent a VB.net interface that has properties and events.
0
2693
by: Mark Parter | last post by:
I'm trying convert an XML Schema (http://www.elframework.org/projects/xcri/efc_r1.0.xsd/view) to a VB.Net class using the XSD tool provided with the .NET 2 SDK. However, it's failing to generate the class and is outputting the following error(s); Schema validation warning: Undefined complexType 'http://purl.org/dc/elements/1.1/:SimpleLiteral' is used as a base for complex type extension. Line 433, position 5. Schema validation warning:...
3
4101
by: Steve Amey | last post by:
Hi all I am using reflection to read the values of properties from a class. The class is returned from a Web Service so I have to access the class using FieldInfo (Using VS 2003 which converts the Properties into Fields when it comes out of the Web Service). I have this at the moment: Private _aDataSource As Object 'Person class
3
3384
by: ajay2552 | last post by:
Hi, I have a query. All html tags start with < and end with >. Suppose i want to display either '<' or '>' or say some text like '<Company>' in html how do i do it? One method is to use &lt, &gt ,&ltCompany&gt to display '<', '>' and '<Company>' respectively. But is there any freeware code available which could implement the above functionality without having to use &gt,&lt and such stuff???
2
2059
by: -Karl | last post by:
Couls someone please advise me on this error. What I am trying to do is be able to convert an XML document into arrays. I read that the subs & functions have to be in <scripttags. Thanks! Error: BC30456: 'Read_DOM' is not a member of
5
3742
by: furqi | last post by:
hi every body i write a code in c sharp in which i have made a base class and make an event there.Then i make a derived class and made an other event in that class. Now what i wanna do is that i wanna invoke in derived class method the base class event but i am facing an error there i am unable find the solution.canaby body tell me the solution.following is the code. using System; using System.Collections.Generic; using System.Linq;...
0
9655
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10363
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10172
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9964
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7517
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5398
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5535
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.