byte_slave
byte_slave

Reputation: 1378

jquery + prepend text not working

I have this following code:


$(".preview").find("#panel").each(function(i, val) {
    var x = "" + $(val).html();
    $(x).find(".dmPageHeadline").prepend(" 1 - ");
    console.log($(x).html());
    html += $(x).html();
});

This code iterates through all accordion panels, concatenates its content and add " 1 - " to the header ( class "dmPageHeadline" ). Probably it's a simple detail, but i cannot figure it out... this line

$(x).find(".dmPageHeadline").prepend(" 1 - ");
doesn't preprend the desired text.

Anyone can point me out what is wrong here?

Thank you very much and happy new year ! Teixeira

Upvotes: 1

Views: 3590

Answers (2)

Nick Craver
Nick Craver

Reputation: 630627

In your code you have #panel and you say you're looping through them...this shouldn't be the case though, an ID needs to be unique, otherwise you'll get all sorts of weird or non-existent behavior.

Instead give the elements a class="panel" instead of id="panel". As for the jQuery side, you can simplify it down to:

$(".preview .panel .dmPageHeadline").prepend(" 1 - ");​

Here's a working example of this in action

If you wanted the index to climb, then do something like this:

$(".preview .panel .dmPageHeadline").each(function(i) {
  $(this).prepend(" " + i + " - "); //maybe (i+1) if you want 1 and not 0 first.
});

The .prepend() function can take a string, it's just the way you were prepending that was a little odd :)

Upvotes: 2

K Prime
K Prime

Reputation: 5849

It because prepend expects either HTML, CSS selector, DOM Node or jQuery object. Try this instead:

$(x).find(".dmPageHeadline").prepend (document.createTextNode(" 1 - "));

Upvotes: 1

Related Questions