Jonathan Wood Jonathan Wood - 3 months ago 7
HTML Question

Insert child elements before inner text

I have the following jQuery/JavaScript code. It adds several elements to an existing

<div>
. It works fine except that I'd like the text to be inserted after the first image.

Does jQuery provider a simple syntax to add the child
<img>
element before the inner text? I know I can create the elements separately but I'd like to keep the expressions as simple as possible.



var div = document.getElementById("div");

var attachmentDiv = $('<div />', { 'class': 'Attachment' });
attachmentDiv.append($('<a />', { href: '#', title: 'Download Attachment', text: 'Filename.ext' })
.append($('<img />', { src: 'https://cdn0.iconfinder.com/data/icons/typicons-2/24/spanner-128.png', 'class': 'AttachmentIcon', alt: 'File Attachment' })));
attachmentDiv.append($('<a />', { href: '#', title: 'Delete Attachment', 'data-id': '000' })
.append($('<img />', { src: 'https://cdn0.iconfinder.com/data/icons/typicons-2/24/spanner-128.png', 'class': 'AttachmentDeleteIcon', alt: 'Delete Attachment' })));
$(div).append(attachmentDiv);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div"></div>




Answer

var div = document.getElementById("div");

var attachmentDiv = $('<div />', { 'class': 'Attachment' });
attachmentDiv.append($('<a />', { href: '#', title: 'Download Attachment', text: 'Filename.ext' })
    .prepend($('<img />', { src: 'https://cdn0.iconfinder.com/data/icons/typicons-2/24/spanner-128.png', 'class': 'AttachmentIcon', alt: 'File Attachment' })));
attachmentDiv.append($('<a />', { href: '#', title: 'Delete Attachment', 'data-id': '000' })
    .append($('<img />', { src: 'https://cdn0.iconfinder.com/data/icons/typicons-2/24/spanner-128.png', 'class': 'AttachmentDeleteIcon', alt: 'Delete Attachment' })));
$(div).append(attachmentDiv);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div"></div>

Comments