Olkunmustafa
Olkunmustafa

Reputation: 3203

appendTo not working in jQuery code?

I'm trying to add a paragraph to an h2 tag using an id selector. However, for some reason it's not working properly. Would someone help me with this?

I have a fiddle I did to try it. See: http://jsfiddle.net/ahLqZ/4/

Here is my code below:

 $(document).ready(function(){

        $("#cevre h2").appendTo($(this).next("p"));

    })​

Upvotes: 0

Views: 409

Answers (1)

Manse
Manse

Reputation: 38147

Try this :

$("#cevre h2").each(function() {
     $(this).appendTo($(this).next("p"));
});

Uses .each() to iterate over the h2 elements - then $(this) becomes each h2 element rather then that document element

Working example here

Note using appendTo on an already existing DOM element moves it ... what you probably wanted (maybe not) was this :

$("#cevre h2").each(function() {
     $(this).clone().insertAfter($(this).next("p"));
});

Uses .clone() to create a clone of the h2 first and .insertAfter() to insert the newly cloned DOM element after the <p> element rather then within it ...

Working example here

Another Note - its not valid HTML to have duplicate id attributes in a single page ... I recommend you change <div id="cevre"> to <div class="cevre"> ... your jQuery selector then becomes $(".cevre h2")

Yet another note - you should cache jQuery objects if they are used multiple times :

$(".cevre h2").each(function() {
     var $this = $(this);
     $this.clone().insertAfter($this.next("p"));
});

Upvotes: 4

Related Questions