views:

76

answers:

4

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/"&gt;MyDomain.com&lt;/a&gt;
    <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.

+4  A: 
$('.theAClass').after('<button>...</button>')

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

Jamie Macey
You forgot the period before the class name in your selector.
alex
alex: so true. fixed.
Jamie Macey
+3  A: 
//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>');
micahwittman
+2  A: 

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');
alex
A: 

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.

cletus
I would argue Cletus that this is neater for the attr() method `.attr({ type: 'button', value: 'Do Stuff' })`
alex
@alex: true, added.
cletus