473,379 Members | 1,245 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,379 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 2689
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: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
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: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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...

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.