0

I'm working on a Greasemonkey script, and I have roughly the following:

Javascript:

var togglingLink = document.createElement("a");
$(togglingLink)
    .attr('href', 'somelink')
    .html('<div>foo</div><div style="display:none">bar</div>');

$(togglingLink).children().toggle();
// Then I insert it into the page.

Which makes this HTML:

<a href="somelink">
    <div>foo</div>
    <div style="display:none">bar</div>
</a>

The $().toggle() is only making the hidden div visible, it's not hiding the visible div. What am I missing here?


James' jsfiddle does work. But the same code in my Greasemonkey script isn't working.

Per bobek's answer, I also tried changing the divs into spans, and that didn't fix it for me.

Community
  • 1
  • 1
Keen
  • 1,327
  • 1
  • 17
  • 25

2 Answers2

2

I finally figured this out. I was actually running $().toggle(); prior to appending the element to the page. This is what was causing jQuery to not toggle as expected. Once I made it the $().toggle(); happened after appending, then it worked properly.

Keen
  • 1,327
  • 1
  • 17
  • 25
1

Having a <div> inside <a> is not valid in HTML < 5 and some browsers might not be able to work with it. Change your <div> to <span> and see if it works then.

bobek
  • 8,003
  • 8
  • 39
  • 75
  • It seems to be valid in HTML5. Go here http://validator.w3.org/#validate_by_input then paste ` a
    a
    `.
    –  Nov 01 '13 at 20:27
  • @wared Yes but not in older versions. If he's doing it in IE8 it might not work. – bobek Nov 01 '13 at 20:29
  • I'm doing this in Firefox 24. – Keen Nov 01 '13 at 20:33
  • Tried with Firefox 25.0, works fine. Does toggle on other elements (non-nested) work for you? – Johannes H. Nov 01 '13 at 20:38
  • @JohannesH. Yeah, toggling random elements in the webpage works fine. For some reason my visible div refuses to hide in my script. – Keen Nov 01 '13 at 21:08
  • Are you sure that there is no additional CSS applied in your actual code that might interfere? Depending on how you're telling Greasemonkey/Scriptish to execute the code, it might get loaded afterwards and make that div visible again. It's clear this is not a pure JS issue if the fiddles work - so some additional background info might help. – Johannes H. Nov 01 '13 at 21:22
  • @JohannesH. I'll work on that over the weekend. It's part of a 150-line script, and I thought I'd pared it down to the key elements here. Obviously I missed something. – Keen Nov 01 '13 at 21:43