1

I have h1 tag, which id called "step1". I would like to add link for that with Javascript. So i trying to code with javascript as follow:

    div = document.getElementById('step1');
 newlink = document.createElement('a');
  newlink.setAttribute('class', 'heading');
 newlink.setAttribute('href', 'javascript:showStep(2);');
 div.appendChild(newlink);

But it render only this way. <h2 id="step1">Step<a href="javascript:showStep(1);" class="heading"> in HTML.

Actually I want following result as :

    <h2 id="step1"><a href="javascript:showStep(2);" 
class="heading">Choose Desired Services</a></h2>

So please help me to create this.

1
  • I don't know what you did, but your code works fine in my firefox 3.17, even with my IE6. Commented Jun 7, 2011 at 13:55

1 Answer 1

2

If you're just adding an element to trigger some JavaScript behavior, there's absolutely no need for it to be an <a> tag. Just make a <span> and set its "onclick" attribute to the function you want to call:

var div = document.getElementById('step1');
var newlink = document.createElement('span');
newlink.onclick = function() { showStep(2); };
newlink.innerHTML = "Choose Desired Services";
div.appendChild(newlink);

You can also give it a class name etc. so that it can be styled appropriately (pointer cursor, whatever).

Also, don't forget var!!

Sign up to request clarification or add additional context in comments.

3 Comments

but it created as follow. <h2 id="step1">Choose Desired Services<span>Choose Desired Services</span></h2>. I want this only. <h2 id="step1"><span>Choose Desired Services</span></h2>
i got it :) I added following code: newlink.innerHTML = "Choose Desired Services"; div.innerHTML = " "; div.appendChild(newlink);
Ah I see - yes, that will do it. I didn't realize that the text was already there in your <h1>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.