页面存在指定ID div时在.content前插入书签链接的jQuery问题
Got it, let's break down the issues with your code and get it working properly:
1. First, Fix the Invalid ID in Your HTML
Your current HTML has <div id="#bookmark">—but the # is only used in CSS/jQuery selectors, not in the actual id attribute value. Change that to:
<div id="bookmark"><a name="bookmark"></a></div>
This way, jQuery's $("#bookmark") selector will actually find the element.
2. Correct the .content Selector
In your jQuery code, you wrote $("content")—this tries to select a <content> HTML tag, not the div with class content. You need to add a dot (.) to target a class:
$(".content") // This selects the div with class="content"
3. Pick the Right jQuery Method for Your Need
You mentioned you want to insert the bookmark link before the .content div (outside of it, not inside). Here's how to use the right methods:
- Option 1: Use
.before()(most straightforward)
Call this on the.contentelement to insert your link right before it:if ($("#bookmark").length > 0) { $(".content").before('<p><a href="#bookmark" class="bookmark-anchor">Jump To Section</a></p>'); } - Option 2: Use
.insertBefore()(reverse order)
With this method, you create the new element first, then tell it to insert itself before the.contentdiv:if ($("#bookmark").length > 0) { $('<p><a href="#bookmark" class="bookmark-anchor">Jump To Section</a></p>').insertBefore(".content"); }
Quick Note on .prepend()
If you wanted to insert the link inside the .content div, at the very top (as the first child element), that's when you'd use .prepend(). But based on your description, .before()/.insertBefore() are what you need.
Full Working Code
Corrected 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>
Corrected jQuery
// Check if the bookmark element exists if ($("#bookmark").length > 0) { // Insert link before .content div $(".content").before('<p><a href="#bookmark" class="bookmark-anchor">Jump To Section</a></p>'); }
内容的提问来源于stack exchange,提问作者user2589071

