issues with jquery prepend

1.8k Views Asked by At

i'm at a loss for why this isn't working..

this works:

$(this).prepend("<div data-role='header'><h1>Hi</h1></div>");

however when i do this my entire page goes blank (nothing loads), but there's no error:

$(this).prepend("<div data-role='header'><a href='link'>Link</a><h1>Hi</h1></div>");

this also doesn't work:

$(this).prepend("<div data-role='header'><h1>Hi</h1></div>");
$(this).find('div[data-role=header]').prepend("<a href='link'>Link</a>");

nor does this:

var string = "<div data-role='header'><a href='link'>Link</a><h1>Hi</h1></div>";
$(this).prepend(string);

and here's the context in case that matters:

$('div[data-role*="page"]').each(function (i) {
    if ($(this).children('div[data-role*="header"]').length != 0) {
        alert("has header");
    } else {
        if (i == 0) {
            var string = "<div data-role='header'><a href='link'>Link</a><h1>Hi</h1></div>";
            $(this).prepend(string);

        } else {
            $(this).prepend("<div data-role='header'><h1>Hi</h1></div>");
        }
        $(this).find('div[data-role=header]').page();
    }
});

how do i get this to work?

3

There are 3 best solutions below

0
On

Assuming you're using version 1.4 or greater, try dynamically creating the elements you need using the new element creation syntax introduced:

$('<a />', {
    'href': 'http://www.google.com',
    'target': '_blank',
    'text': 'This is a link',
    'class': 'myClassName',
    'css': {
        'top': '20px'
    }
           }).appendTo('<div />', { 'data-role': 'header' })
             .prependTo($(this));
2
On

I am guessing you are using jQuery mobile it appears it works as intended on jsfiddle. What browser are you testing this on?

Updated jsfiddle to be a more complete example so the page transition works from the first page.

0
On

In my experience, if the script in which the prepend function is used in the -tag, it will not work because the script is loaded before the DOM is ready.

To avoid this kind frustration, is a good habit to place your javascript before the tag.