0

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"));

    })​
2
  • 2
    You have id's repeating across elements and it is invalid. element id's should be unique Commented Jul 17, 2012 at 15:26
  • This is your second question on stackoverflow - please learn how to accept answers ... if you have no idea what I'm talking about click here Commented Jul 17, 2012 at 15:33

1 Answer 1

4

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"));
});
Sign up to request clarification or add additional context in comments.

3 Comments

Also, the OP probably wants insertAfter(), not appendTo().
@Juhana yes your are probably right .. updated my answer ... thanks
@thirtydot - this is very ironic - i just posted an answer telling someone to add the var keyword to prevent polluting the global namespace - then I do it .... thanks for the edit ...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.