473,385 Members | 1,890 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

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.createElement('ul');
ul.className = 'cdTrack';

....
for(var j=0; j<titleTrackElems.length; j++)
{
li = document.createElement('li');

liValue =
document.createTextNode(titleTrackElems.item(j).ch ildNodes[0].nodeValue);
li.appendChild(liValue);

a = document.createElement('a');
a.setAttribute('href', '#');
aValue = document.createTextNode(...);
a.appendChild(aValue);
a.onclick = function () { a.className='here'; };

li.appendChild(a);
}

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

Thanks
Marco

May 23 '07 #1
5 2692
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.createElement('ul');
ul.className = 'cdTrack';

...
for(var j=0; j<titleTrackElems.length; j++)
{
li = document.createElement('li');

liValue =
document.createTextNode(titleTrackElems.item(j).ch ildNodes[0].nodeValue);
li.appendChild(liValue);

a = document.createElement('a');
a.setAttribute('href', '#');
aValue = document.createTextNode(...);
a.appendChild(aValue);
a.onclick = function () { a.className='here'; };
this.className;

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

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript 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.createElement('ul');
ul.className = 'cdTrack';
...
for(var j=0; j<titleTrackElems.length; j++)
{
li = document.createElement('li');
liValue =
document.createTextNode(titleTrackElems.item(j).ch ildNodes[0].nodeValue);
li.appendChild(liValue);
a = document.createElement('a');
a.setAttribute('href', '#');
aValue = document.createTextNode(...);
a.appendChild(aValue);
a.onclick = function () { a.className='here'; };

this.className;

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

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ -http://jibbering.com/faq/index.html
Javascript Best Practices -http://www.JavascriptToolbox.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.comwrote:
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.createElement('ul');
ul.className = 'cdTrack';
...
for(var j=0; j<titleTrackElems.length; j++)
{
li = document.createElement('li');
liValue =
document.createTextNode(titleTrackElems.item(j).ch ildNodes[0].nodeValue);
li.appendChild(liValue);
a = document.createElement('a');
a.setAttribute('href', '#');
aValue = document.createTextNode(...);
a.appendChild(aValue);
a.onclick = function () { a.className='here'; };
this.className;
And then ask about "this" and the issue that will arise from it.
--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ -http://jibbering.com/faq/index.html
Javascript Best Practices -http://www.JavascriptToolbox.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.comwrote:
On May 25, 7:13 pm, SM <servandomont...@gmail.comwrote:
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.createElement('ul');
ul.className = 'cdTrack';
...
for(var j=0; j<titleTrackElems.length; j++)
{
li = document.createElement('li');
liValue =
document.createTextNode(titleTrackElems.item(j).ch ildNodes[0].nodeValue);
li.appendChild(liValue);
a = document.createElement('a');
a.setAttribute('href', '#');
aValue = document.createTextNode(...);
a.appendChild(aValue);
a.onclick = function () { a.className='here'; };
this.className;
And then ask about "this" and the issue that will arise from it.
--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ -http://jibbering.com/faq/index.html
Javascript Best Practices -http://www.JavascriptToolbox.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.prototype.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.className)) {
el.className += (' ' + className).trim();
}
}

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

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

// 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.toLowerCase() != tagName) {
el = el.parentNode;
}
return (el.tagName &&
el.tagName.toLowerCase() == tagName)? el : null;
}

// Highlight the last A element that was clicked on
function highLightLastLink(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.getElementsByTagName('a');
var i = aElements.length;
while (i--){
xU.removeClass(aElements[i], 'red')
}

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

window.onload = function(){
document.body.onclick = highLightLastLink;
}
--
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.comwrote:
On May 25, 7:13 pm, SM <servandomont...@gmail.comwrote:
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.createElement('ul');
ul.className = 'cdTrack';
...
for(var j=0; j<titleTrackElems.length; j++)
{
li = document.createElement('li');
liValue =
document.createTextNode(titleTrackElems.item(j).ch ildNodes[0].nodeValue);
li.appendChild(liValue);
a = document.createElement('a');
a.setAttribute('href', '#');
aValue = document.createTextNode(...);
a.appendChild(aValue);
a.onclick = function () { a.className='here'; };
this.className;
And then ask about "this" and the issue that will arise from it.
--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ -http://jibbering.com/faq/index.html
Javascript Best Practices -http://www.JavascriptToolbox.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.prototype.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.className)) {
el.className += (' ' + className).trim();
}

}

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

}

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

}

// 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.toLowerCase() != tagName) {
el = el.parentNode;
}
return (el.tagName &&
el.tagName.toLowerCase() == tagName)? el : null;

}

// Highlight the last A element that was clicked on
function highLightLastLink(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.getElementsByTagName('a');
var i = aElements.length;
while (i--){
xU.removeClass(aElements[i], 'red')
}

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

}

window.onload = function(){
document.body.onclick = highLightLastLink;

}

--
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
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...
2
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...
0
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...
2
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. : ...
0
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...
0
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...
3
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...
3
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,...
2
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! ...
5
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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,...
0
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...

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.