views:

76

answers:

2

The HTML code:

<ul id="el">
   <li></li>
   <li></li>
   <li></li>
   <li></li>
</ul>

How to create new element span inside li element on mouseover?

<ul id="el">
   <li></li>
   <li></li>
   <li><span></span></li><!--on mouseover > new element span-->
   <li></li>
</ul>
+1  A: 
document.getElementById('el').addEventListener("mouseover", function(e){
  var e=e.target;
  if (e.nodeName=="LI") {
    var span=e.getElementsByTagName('span')[0];
    if(!span) {
      e.innerHTML="<span></span>";
    }
  }
},false);

This will do a check for an existing SPAN before inserting it. In addition it does not require JQuery or any other JS framework.

Tested on Firefox, but some browsers might handle the e.target part differently so just bear that in mind.

michael
Your example does not work.
Binyamin
No. My example DOES work. I tested it in Safari 5.0.1, Firefox 3.6.8, and Chrome 5.0.375.See this link for Javascript with HTML: http://ifelse.org/projects/stackoverflow/3417148.html If you cannot get it to work I would appreciate the courtesy of detailing how you implemented it so I can verify.
michael
;) works fine in http://ifelse.org/projects/stackoverflow/3417148.html
Binyamin
Glad to hear it. The original code posted wouldn't show any visual change (you'd have to use Firebug etc to see it) since I worked with the sample HTML you gave me. Was that the problem? Out of curiosity, if it had 'worked' for you, would I have been give the 'best answer'? :)
michael
I asked for Mootools solution not usual JS. Thanks for your post anyway!
Binyamin
You're welcome. Minor point: while you tagged it mootools, you didn't clarify it MooTools until after I posted. Also, I don't see why it should be mootool specific when normal JS works as it. Swapping 'document.getElementById' etc with $ isn't a huge deal. All the best
michael
+1  A: 

try with this:

document.getElements('#el > li').addEvent('mouseenter', function(e) {
  var target = document.id(e.target);
  if (!target.getElement('span')) target.adopt(new Element('span'));
});

if you want to remove the span on mouse out, then add this:

document.getElements('#el > li').addEvent('mouseleave', function(e) {
  document.id(e.target).getElements('span').destroy();
});

be careful as these are very naive implementations and are the bare minimum you need for it to work.

gonchuki
Thanks, it works well!
Binyamin