Vergil C.
Vergil C.

Reputation: 1104

How do I append an element after a specific element using jquery with an object as the target?

I want to append an element of H2 <h2>H2</h2> to the html as shown below

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
    <div id="a">
        <h1>H1</h1>
        <!--I want to add H2 here-->
        <h3>H3</h3>
    </div>
    <div id="b">

    </div>
</body>
</html>

I query the div like this var mydiv = $("#a")[0]; and then I want to append <h2>H2</h2> inside myDiv, but after <h1>H1</h1> OR before <h3>H3</h3>. I have played around a bit with after(), insertAfter(), before(), insertBefore() with no luck, because i want to target and use the object 'myDiv' and not the whole html page.

EDIT: Some things I have tried

I have tried the following:

var myDiv = $("#a")[0]
$(myDiv).append("<h2>H2</h2>")

This adds the element to the end of the div

Also tried this:

$("h1").after("<h2>H2</h2>")

This adds <h2>H2</h2> after every <h1>H1</h1> which is not what I need to do, I need to add <h2>H2</h2> only inside the selected div which in this case is myDiv

Upvotes: 4

Views: 6970

Answers (2)

gamusino
gamusino

Reputation: 1

Your code is correct, only need change the selector adding h1 in the myDiv selector.

Example:

var myDiv = $("#a h1")[0] $(myDiv).after("<h2>H2</h2>")

Upvotes: 0

ponury-kostek
ponury-kostek

Reputation: 8060

Use jQuery#after and jQuery#find

var myDiv = $("#a")[0];
$(myDiv).find('h1').after("<h2>H2</h2>");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="a">
  <h1>H1</h1>
  <!--I want to add H2 here-->
  <h3>H3</h3>
</div>
<div id="b"></div>

or

$("#a").find("h1").after("<h2>H2</h2>");

or

$("#a h1").after("<h2>H2</h2>");

Upvotes: 4

Related Questions