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”

Pages: « 1 [2] Show All

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

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

Pages: « 1 [2] Show All

Leave a Reply

Spam protection by WP Captcha-Free