1

I have this code:

jQuery('.post-single-content').addClass('padT');            
jQuery('.post-single-content').css("padding-top", "40px");

It basically converts this:

<div class="post-single-content">

into this:

<div class="post-single-content padT" style="padding-top: 40px;"> 

I am however trying to change the code so it converts it into something like this:

<div class="post-single-content">
<a href="../index.html"><img src="../spacer.jpg"></a>

Could someone tell me how to do this. I've tried to use a few examples from here but had no luck. Any help would be appreciated.

4 Answers 4

1

Use append, llike this:

$('.post-single-content').append('<a href="../index.html"><img src="../spacer.jpg"></a>');

CODEPEN DEMO

1
  • 1
    Thank you! It work :). I ended up using .prepend instead of .append to get it to appear at the start of the div tag.
    – Ron
    Commented Apr 20, 2015 at 16:16
1

You may use jQuery to dynamically create new DOM objects and append them to an existing one:

var div = $('.post-single-content');
var link = $('a').attr('href', '../index.html');
var image = $('img').attr('src', '../spacer.jpg');
div.append(link.append(image));
1

You can use the function after()

$(".post-single-content").after( '<a href="../index.html"><img src="../spacer.jpg"></a>' );

This solution adds the element after the .post-single-content div. You should use append():

$(".post-single-content").append( '<a href="../index.html"><img src="../spacer.jpg"></a>' );
1
  • 1
    This solution would add the new content after the div, and not inside in it. You might want to use append instead.
    – mcserep
    Commented Apr 19, 2015 at 0:11
1

If it's just a single div you are trying to manipulate add an id.

<div id="divToChange" class="post-single-content padT" style="padding-top: 40px;"></div>

Then create the elements and append (a little more verbose than the other solutions, but never hurts to see a different way).

$(document).ready(function () {

    var targetDiv = $('#divToChange');

    var aTag = document.createElement('a');
    aTag.href = '../index.html';

    var imgTag = document.createElement('img');
    imgTag.src = '../spacer.jpg';

    $(imgTag).appendTo(aTag);
    $(aTag).appendTo(targetDiv);
});

Results in the following:

<div id="divToChange" class="post-single-content padT" style="padding-top: 40px;"><a href="../index.html"><img src="../spacer.jpg"></a></div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.