Tuesday, April 5, 2011

Inserting HTML as a last child of a selected tag using JQuery

I am new to JQuery. I'm reading JQuery in action, but only up to page 39 and need some quick help!

Please note: I'm simplifying my actual requirement, so what I'm asking for may sound odd but I'm just tryin to get to the crux of the JQuery expression and not my situation (related to an animation plugin).

I have my HTML code (which is generated and I dont want to change) :

<div class="favorite">
   <div>
          <a href='http://www.stackoverflow.com'>Stackoverflow</a>
   </div>
</div>

Now that I want to do is insert the text '(favorite)' INSIDE the A tag after the current contents. Or in other words as the last child of the <a>.

<div class="favorite">
   <div>
          <a href='http://www.stackoverflow.com'>Stackoverflow (favorite)</a>
   </div>
</div>

The best I have so far is this :

$('<span> (favorite)</span>').insertAfter('.favorite div a');

Of course this ends up putting the (favorite) text OUTSIDE the A link and it wont be underlined (which I want).

I need to somehow say .parent().lastChild() but I'm not quite sure how to do that.

Note: I had to put <span> in because otherwise it didnt see it as 'insertable' text. I'm sure there a way around that too but thats a secondary concern.

From stackoverflow
  • The append method inserts nodes at the end of match elements. Prepend inserts nodes at the beginning.

    Example:

    $('div.favorite div a').append('<span> (favorite)</span>');
    

    The span element isn't necessary - you can just do this:

    $('div.favorite div a').append(' (favorite)');
    
    Simon_Weaver : oops! I had actually tried append and it appeared to do NOTHING. turns out this is because my animation was relying on a css selector for '.favorite div a' which contains 'display:none'. So it was workin but instantly vanishing itself. thanks
    Simon_Weaver : plus in addition i had got the two clauses the wrong way round - which was key. so i had only almost got it working
  • You can also do:

    $("div.favorite div a").text($("div.favorite div a").text() + " (favorite)");
    
    Simon_Weaver : thats making my head spin :)
    Birk : haha, yeah, but it *is* an option :)

0 comments:

Post a Comment