GregH
GregH

Reputation: 12868

jQuery Inserting a Button After An Anchor

How in jQuery would I add a button directly after an anchor tag? For example, my HTML looks like:

<div style="border-style: solid; border-width: thin; padding: 2px;">
  <center>
    <a target="_blank" href="http://www.mydomain.com/">MyDomain.com</a>
    <b>My Hypertext Link</b>
    <br/>
    Options:
   <a class="theAClass" href="#">Insert button after this anchor</a>
  </center>
</div>

I want to add a button just after the anchor (class="theAClass") but before the "center" tag so the button is centered on the page.

Upvotes: 2

Views: 11105

Answers (4)

Jamie Macey
Jamie Macey

Reputation: 3002

$('.theAClass').after('<button>...</button>')

Should do the trick. That will append the html you specify immediately after the tag.

Upvotes: 10

cletus
cletus

Reputation: 625097

You can do it with after():

$("a.theAClass").after("<input type='button' value='Do Stuff'>");

or with insertAfter():

$("<input type='button' value='Do Stuff'>").insertAfter("a.theAClass");

The benefit of the second method is you can do this:

$("<input></input>").attr("type", "button").attr("value", "Do Stuff")
  .insertAfter("a.theAClass");

or more simply:

$("<input></input>").attr({type: "button", value: "Do Stuff"})
  .insertAfter("a.theAClass");

That can be advantageous because constructing markup this way will correctly escape special characters and so on whereas the first way needs to manually escape content, which is important if you're including dynamic elements.

Upvotes: 0

alex
alex

Reputation: 490303

Here is also an alternative way, however generating the element like this would probably be a lot slower. It can be neater however when dealing with an element with a lot of attributes.

$('<button />')
    .html('Click me')
    .insertAfter('.theAClass:first');

Upvotes: 2

micahwittman
micahwittman

Reputation: 12476

//Add button after every theAclass link
$('a.theAClass').after('<button type="button">Click Me!</button>');

//Add button after only the first theAclass link
$('a.theAClass:first').after('<button type="button">Click Me!</button>');

Upvotes: 4

Related Questions