Forum Moderators: open

Message Too Old, No Replies

Using Javascript to modify contents of elements targetted by CSS rule

Sounds kind of complex; can it be done?

         

MatthewHSE

7:20 pm on Jan 12, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I need a bit of JavaScript that will go through a page and find all the links targeted by this CSS rule:

a.icon, .icon a { /* Rules go here */ }
(For those unfamiliar with CSS syntax, this means all anchor tags with the class name of 'icon', as well as all anchor tags that are contained within an element with the class name of 'icon'.)

The script then needs to modify the anchor text to add an image after the text.

This is far above my meager JavaScript skills, and while I'm not looking for anybody to code the whole thing for me, it would be nice if someone could at least point me in the right direction! ;)

Thanks in advance,

Matthew

Dabrowski

8:55 pm on Jan 12, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hmmm, it should be fairly easy. I've not done much JS relating to CSS rules, but it should be easy to find that specific rule based on the elements alone.

Try this (untested):

// Get all A tags on page 
var Atags = document.getElementsByTagName( "A");

// Loop through
for( a in Atags) {
var thisA = Atags[ a];
var tag = Atags[ a];
var match = 0;

// Go back up the DOM 1 step at a time, checking class as we go...
// parentNode must be defined at least for the A tag itself
while( tag.parentNode &&!match) {

// If classname of this element matches...
// Note, the first element will be an A, so this will match "A.icon"
if( tag.className == "icon")
match = 1;

// Move 1 level up the DOM
// If any parent has a class of icon, this will match ".icon a"
tag = tag.parentNode;
}

// Try next A tag if no match
if(!match) continue;

// Add your extra HTML like this....
thisA.innerHTML += "<img ...>";
}

MatthewHSE

3:39 pm on Jan 14, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hey, thanks, this is exactly what I needed!

One minor issue is that the script needs to be at the very bottom of the page in order to work, just above the closing BODY tag. Is there any way I can bundle this into my site-wide Javascript file, which is included in the HEAD section?

Dabrowski

3:48 am on Jan 15, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yes that's an easy one.

Wrap that code in a function, like:


function addIcons() {
// PUT THAT CODE IN HERE!
}

And add that function into your site wide javascript. Then, to execute it add this line at the end of your HTML:

<script> addIcons(); </script>