tags:

views:

133

answers:

5

I have something like this: ...

<div id="d120" >content</div>
<div id="d123" >content</div>
<div id="d112" >content</div>
<div id="d145" >content</div>
<div id="d134" >content</div>
//Insert here hello world

<div id="bla" >asd</div>
<div id="footer" >asd</div>

anybody knows how to insert html after all the divs that have id like d+number

A: 

add another div with an id and then just change the html for that element $('#id').html('html');

unless that will break your page layout?

A: 

Try this:

$(function(){
  $('div[id^="d"]:last').after('<div>Hello World</div>');
});

Note: As suggested by Nick Craver, this would match any div whose id starts with d but i think that's what you have to resort to as per your html markup.

Sarfraz
+1  A: 
$("div[id^=d]:last").after("some html");

or:

$("some html").insertAfter("div[id^=d]:last");
karim79
Do you really think this is a safe approach?
patrick dw
not really, there at least needs to be a couple more characters at the start of the IDs to eleminate the potential for a *natural* disaster (other divs with id starting with d). I reckon they should be assigned a common class instead.
karim79
+2  A: 

If the format doesn't have anything between those divs and #bla like your example, here's a safer approach using .before() (since div[id^=d] would match <div id="doodlesticks"> as well).

$("#bla").before("<b>Hi There</b>");

Update: Since you said it's possible to give them a class, I'd do that, so give the content divs a class="content" and use this jQuery:

$(".content:last").after("<b>Hi There</b>");
Nick Craver
no bla was just to show that there is something else in there, but i don't know what is going to be, although it's a good idea to
Omu
@Omu - possible to give those content divs a class? Matching just on a starting `d` isn't all that safe, what else you have to work with?
Nick Craver
yes, it is possible to give them a class
Omu
@Omu - I'd give them a class then, and use `$(".MyClass:last").after(htmlStringHere);`, updated the answer to show this approach.
Nick Craver
+3  A: 

This will safely test for elements whose id ends with a number, instead of any id that start with "d".

$('div[id]').filter(function() {
    return /\d+$/.test($(this).attr('id'));
}).last().after(...my html...);
patrick dw
+1: This looks to be more generic solution as per the html markup and requirement of the OP.
Sarfraz