Javascript Create A Hyperlink Element

Creating a hyperlink element using Javascript is pretty simple. Do the following. Notice, that the hyperlink element contains two text ‘click me’ that’s been set twice. This is because IE only accepts its proprietary innerText property to set a hyperlink’s text while other browsers use textContent. To set a CSS class name, you need to use the className attribute because the class property is a reserved word in Javascript. You can either use it as element.classname = 'class_name' or element.setAttribute('className', 'class_name');

<body>
<div id="div"></div>
</body>
<script>
div = document.getElementById('div');
 
a = document.createElement('a');
a.innerText = 'click me';
a.textContent = 'click me';
a.href = 'javascript://';
a.setAttribute('className', 'more_right');
a.setAttribute('onclick', 'alert("clicked");');
 
div.appendChild(a);
</script>

Donations appreciated. Every little $ helps. Or click Google +1

Related Posts with Thumbnails

tags: , ,

7 Responses to “Javascript Create A Hyperlink Element”

  1. 1
    anneberly Says:

    you will make more money if you will use your knowledge in creating a business website that can be interesting for a lot of people. Why dont you make a website where can poeple can view movies for free.

    Computer and Electronics
    Personal Blog Money
    Seek Health. Feel Great

  2. 2
    tech Says:

    i don’t think i have the finances for that anne he he he

  3. 3
    Darius Caughron Says:

    I have read a few of the articles on your website now, and I really like your style of blogging. I added it to my favorites blog site list and will be checking back soon. Please check out my site as well and let me know what you think.

  4. 4
    Chelsey Fjeseth Says:

    thank you for your article,My problem has been resolved.

  5. 5
    Dallas Tanner Says:

    This is exactly what I have spent a day to find, but can’t seem to make it work. It loads the page without error, but no link appears. How do you apply it in a web page?

    Thanks in advance…

    Here is what I put together from what you posted:

    div = document.getElementById(‘div’);

    a = document.createElement(‘a’);
    a.innerText = ‘click me’;
    a.textContent = ‘click me’;
    a.href = ‘javascript://’;
    a.setAttribute(‘className’, ‘more_right’);
    a.setAttribute(‘onclick’, ‘alert(“clicked”);’);

    div.appendChild(a);

  6. 6
    Dallas Tanner Says:

    Sorry - I did copy the whole page, but that’s not what it posted. Could you just use the code in a working example for newbies like me to mimic? Thanx again!

  7. 7
    tech Says:

    @Dallas: hi. the html code was a shortcut, i figured having the div tags alone would work. you can add tags between the div tags.

    i updated the html code above

Leave a Reply

Spam protection by WP Captcha-Free