Search code examples
jqueryparent-childinsertafter

jQuery Child Selector by class


I have the following html structure, and would like to insert a div using jQuery in the indicted place.

<div class="item" data-url-id="intro">
    <div class="title-wrapper">      
        ...
    </div>
    <!-- want to insert the element here -->
    <div class="content-wrapper">
        ...
    </div>
</div>

I'm using this code:

$( "div[class='item'][data-url-id='intro'] > div[class='title-wrapper']" ).after( "<div class='...'>...</div>");

Essentially, the 'inside' div's do not have ids, and must thusly be identified by class.

I thought the above meant "insert an element after a div of class 'title-wrapper' that is a child of a div with class 'item' AND an attribute of 'data-url-id' who's value is 'intro'".

Any thoughts are greatly appreciated!

Regards,

Zephyr


Solution

  • The jquery selectors can be simplified a little bit:

    $('.item[data-url-id=intro] > .title-wrapper').after('<div>Inserted Element</div>');

    Here's a working jsfiddle: http://jsfiddle.net/2ys5j0ac/