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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! It work :). I ended up using .prepend instead of .append to get it to appear at the start of the div tag.
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));

Comments

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 Comment

This solution would add the new content after the div, and not inside in it. You might want to use append instead.
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>

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.