Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap element then append another element inside it

Tags:

jquery

Look at this code

<div class="preview">
    <img src="link" alt="" class="overlay" />
</div>

what i need to do is to wrap the inside div call "overlay" then append another div called "overlay2" to be like below

<div class="preview">
    <div class="overlay">
        <img src="link" alt="" class="overlay" />
        <div class="overlay2"></div>
    </div>
</div>

i'm tried to use .wrap and append but i didn't know how to use this with one command

like image 747
ahmedsaber111 Avatar asked Oct 16 '12 02:10

ahmedsaber111


People also ask

Which jQuery method allows you to add a wrapper element around another set of elements?

The wrap() method wraps specified HTML element(s) around each selected element.

How do I wrap a div inside a div?

If you've faced the situation when you need to wrap words in a <div>, you can use the white-space property with the "pre-wrap" value to preserve whitespace by the browser and wrap the text when necessary and on line breaks.

What does the jQuery .wrap function do?

wrap( function ) A callback function returning the HTML content or jQuery object to wrap around the matched elements. Receives the index position of the element in the set as an argument. Within the function, this refers to the current element in the set.

What is a wrapped set in jQuery?

A) Definition The wrapped set is simply a list of DOM elements(with their children) in the order in which they are defined in the current document that matches a selector or in the order in which they have been created on the fly with the $(html) function.


2 Answers

You may try this

$('div.preview img')
.wrap('<div class="overlay"></div>')
.after('<div class="overlay2"></div>');

DEMO (See the source).

OR

$('div.preview img')
.wrap($('<div/>', {'class':'overlay'}))
.after($('<div/>', {'class':'overlay2'}));

DEMO (See the source).

Output

<div class="preview">
    <div class="overlay">
        <img src="link" alt="" class="overlay">
        <div class="overlay2"></div>
    </div>
</div>
like image 179
The Alpha Avatar answered Nov 25 '22 03:11

The Alpha


very simple

$('.preview').append('<div class="overlay2"></div>')
$('.overlay').wrap('<div class="overlay"></div>')

test it here: http://jsfiddle.net/RASG/32JSW/

like image 20
RASG Avatar answered Nov 25 '22 03:11

RASG