user2589071
user2589071

Reputation:

Insert HTML Before div Only If Page Contains div id

I need to insert HTML before the .content div for a HTML book mark link BUT only if the page contains a div id for the anchor which is

<div id="#bookmark"><a name="bookmark"></a></div>

Here's the jQuery i wrote which doesn't work and also doesn't produce any errors.

if($("#bookmark").length > 0) {

 $(".content").insertBefore('<p><a href="#bookmark" class="bookmark-anchor">Jump To Section</a></p>');

 }

And here's the HTML

<div class="content">
<p>This is an example of content</p>
<h2>Sub Heading</h2>
<p>This is an example of content</p>
<h2>Sub Heading</h2>
<div id="#bookmark"><a name="bookmark"></a></div>
<p>This is an example of content</p>
</div>

Also, not sure whether whats best to use .insertBefore, .prepend or any other jQuery method.

Upvotes: 0

Views: 631

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115282

The insertBefore() method is using insert the selected element before the other with your current code it will insert ".content" element before the target(HTML string).

To insert some HTML content before ".content" element use before() method.

$(".content").before('<p><a href="#bookmark" class="bookmark-anchor">Jump To Section</a></p>');

If you want to append content at the beginning of an element then use prepend() method.

$(".content").prepend('<p><a href="#bookmark" class="bookmark-anchor">Jump To Section</a></p>');

FYI : Remove the # from the id attribute value to avoid issues and it's only necessary with id selector.

Upvotes: 0

Hien Nguyen
Hien Nguyen

Reputation: 18973

You can use setInterval for your requirement.

let isLoad = setInterval(function () {
   if ($('#bookmark').length > 0) {
                $(".content").insertBefore('<p><a href="#bookmark" class="bookmark-anchor">Jump To Section</a></p>');
                   clearInterval(isLoad)
                }
   }, 500);

Upvotes: 0

4b0
4b0

Reputation: 22321

You have # on div id. No need # on id.Remove that and use prepend like below.

if ($("#bookmark").length > 0) {
  $(".content").prepend('<p><a href="#bookmark" class="bookmark-anchor">Jump To Section</a></p>');

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="bookmark">
  <a name="bookmark"></a>
</div>
<div class='content'></div>

Upvotes: 0

Related Questions