1

I am trying to setup a new "a" component using JS function which is called , using following :

function add_div(data){
    mydiv = document.getElementById("new_twt");
    var link =document.createElement("a");
    var text = "you have new conversations";
    link.setAttribute("name",text);
    link.onclick=function(){new_tweet(data);};
    mydiv.appendChild(link);
  }

Changes are not reflecting on the webpage , however if I use some other element such as button or new div it gets created instantly, am I missing something?

3
  • 1
    Note that unless you're declaring it somewhere, you're falling prey to The Horror of Implicit Globals with mydiv. Commented Dec 6, 2012 at 9:23
  • Other than the (possible) implicit global and the odd name attribute (did you mean title?), provided you have an element with the id "new_twt" when you call add_div, that looks like it should work. Commented Dec 6, 2012 at 9:24
  • Why the jquery tag when you're doing everything with raw JS? Commented Dec 6, 2012 at 9:35

2 Answers 2

1

This works for me:

function add_div(data){
    var mydiv = document.getElementById("new_twt");
    var link = document.createElement("a");
    var text = "you have new conversations";
    link.name = text;
    link.href = '#';
    link.innerHTML = 'link';
    link.onclick=function(){ new_tweet(data); return false; };
    mydiv.appendChild(link);
}
  • I've added link text (innerHTML) so you can actually see the link
  • I've also added "href" so the link behaves as a link (with this you need to prevent default link action, like "return false" in the event listener, to prevent browser from jumping to the top)
Sign up to request clarification or add additional context in comments.

4 Comments

is it necessary to provide link.href and link.innerHTML
"href" is not required, but without "innerHTML" the link will be empty, so unless you've styled it to be visible (display: block, image bg) you will not see the link.
thanks for the help, just in situation i call this function again or thrice the link gets appended 3 times how can I avoid this , i mean is it possible to replace child i.e previous link with same function
give the link a unique ID and before adding it - check if the id exists
1

Try this:

var mydiv = document.getElementById("new_twt");
var aTag = document.createElement('a');
aTag.setAttribute('href',"yourlink.htm"); //or #
aTag.innerHTML = "you have new conversations";
aTag.onclick=function(){new_tweet(data);};
mydiv.appendChild(aTag);

Here is working JS Fiddle.

Comments

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.