views:

485

answers:

4

Is this the correct way to do it?

<a id="load" href="#" class="btn load" onclick="request(this); $('#load').fadeOut(2000)">add</a>

<a href="#" id="test" onClick="alert( 'TEST!' )">here</a>

<script language="javascript">
var requests = 2;

function request(self)
{if(self.href != "#")
requests -= 1;

if(requests === 0)
document.getElementById("test").id= "nextstep";}
</script>

I want id="test" to change to id="nextstep" if the requests = 0.

A: 

You could try:

document.getElementById('test').setAttribute('id', 'nextstep');
marcc
That didn't work at all.
Homework
No need to use `setAttribute` (unless we are talking about XML DOM) `element.id = 'nextstep'` should be enough in this case.
kangax
A: 

That's exactly how you'd go about doing it, as long as you wrap it in script tags...

<script language="javascript" type="text/javascript">
if(requests === 0){
    document.getElementById('test').id = "nextstep";
}
</script>

If you're trying to trigger this on the click of that anchor, then you'd use:

<script language="javascript" type="text/javascript">
function changeID(){
    if(requests === 0){
        document.getElementById('test').id = "nextstep";
        alert('TEST!');
    }
}
</script>

<a href="#" id="test" onclick="changeID()">Test</a>

EDIT: Well you changed the content of your question after I posted this...

BraedenP
Yes, do you understand what I'm trying to do now? haha
Homework
A: 

You need to use 'setAttribute' to change the ID of anchor tag.

You've got the getElementById('test') part right, but just throw ".setAttribute('id','nextstep');"

Hope that helps!

Chris Schmitz
Why doesn't it want to work? ha
Homework
A: 

if(self.href != "#")

There's your problem. Link hrefs are canonicalised by the browser, so a link ‘#’ on page ‘http://www.example.com/’ has an href attribute of ‘http://www.example.com/#’ and does not match the condition.

Avoid using the name ‘self’, as it clashes with the name of the global object (aka ‘window’). You can avoid the clumsy passing in of ‘self’ by assigning the handler from JavaScript:

document.getElementById('load').onclick= request;

instead of the onclick attribute, then you could use ‘this’ in request(). request() should also return false; to stop the link being followed (making the browser scroll to the top). Better still would be to use a <button> (or <input type="button">), because it's an action button and not a link that you could open in a new window or bookmark. (You can always use CSS to make it look less like a button.)

Don't use setAttribute() for HTML, it has problems in IE unrelated to this usage. Setting element.id was already fine.

But this all seems like rather a strange way of going about what you want to do in any case.

bobince