Question

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.

Was it helpful?

Solution

You could try:

document.getElementById('test').setAttribute('id', 'nextstep');

OTHER TIPS

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...

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!

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top