1

I have a very simple piece of jQuery code (jQuery 1.7.1). Though the error below shows up, and the code isn't executed.

Uncaught HierarchyRequestError: A Node was inserted somewhere it doesn't belong.

The code that causes this error is as follows:

counter = 0;
jQuery('h3').each(function(){
    counter += 1;
    div = '<div class="' + counter + '"></div>';
    jQuery(this).after(div);
    jQuery(this).nextUntil('h3').appendTo('div.' + counter);
});

For some reason, the jQuery(this).after(div); causes a problem. It has something to do with the class I am adding to the div (specifically the class, not the variable I set as class). At first I used append instead of after, but that didn't give the desired effect. However, append didn't give an error.

Can anyone clarify why I am not allowed to add a class in the after function, and if possible, give me a good alternative to tackle this problem?

Sander Koedood
  • 6,007
  • 6
  • 25
  • 34

1 Answers1

3

You are trying to insert the div into itself. Indeed, jQuery(this).after(div) results in :

<h3></h3>
<div class="1"></div>
<h3></h3>

So then, jQuery(this).nextUntil('h3') includes the div itself. Here is how to avoid this situation :

jQuery(this).nextUntil('h3')
    .not('div.' + counter)
    .appendTo('div.' + counter);

This has nothing to do with your question, but I wonder if a CSS class beginning with a number is valid or not : https://stackoverflow.com/a/449000/1636522.

Community
  • 1
  • 1
  • You are right (in both the CSS class and the div inserting into itself). It gave me a push in the right direction. Though you didn't really give me a working solution, you did help me solve this problem myself. So I'll accept this answer for that. – Sander Koedood Nov 22 '13 at 13:00
  • It can [Class names with numbers], only in HTML5 though. – MackieeE Nov 22 '13 at 13:00
  • @SanderKoedood Thanks :) I've added a solution. –  Nov 22 '13 at 13:04
  • @MackieeE Link broken :/ –  Nov 22 '13 at 13:07
  • Oh, nice. The exact same solution as I came up with. @MackieeE, I think class names with numbers are still not recommendable, since you'd need to escape the first character to use it. – Sander Koedood Nov 22 '13 at 13:07
  • 2
    @wared It wasn't a link! but here is one =) http://www.w3.org/html/wg/drafts/html/master/dom.html#the-id-attribute "*IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation*" and you're right sanderKoedood I'd never actively say numbers as class names will never really be recommended, but it is doable and thus won't throw errors. – MackieeE Nov 22 '13 at 13:18