5

I am building up an HTML element using

$(this).html(' my html here');

There are many elements I need to add here with different CSS. So what I want is I should be able to do append another HTML here

$(this).html(' my html here');
$(this).html.append(' another html here');

How can I achieve this?

2
  • 1
    Just use $(this).append();. Which is more than enough. Commented Apr 11, 2016 at 9:01
  • This is my exact html $(this).parent().html('<span class=\"asset_value\">'+ new_comment +'</span>.css('color', 'red'); $(this).append('<span id=save onclick=\"update(cellreport_id , new_comment)\" class=\"glyphicon glyphicon-floppy-disk pull-right\">&nbsp;</span>'); Its not working here Commented Apr 11, 2016 at 9:14

2 Answers 2

7

First declare.

var html = "";
html += "<span class="spnBlack"> First Content </span>";
html += "<p class="pRed">Second Content</p>";
$(this).html(html); 

And in css file define

.spnBlack
{
  background-color: black;
}
.pRed
{
  background-color: red;
}

Please avoid inline css.

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

2 Comments

This is good but I also want to add certain css styling to the elements individually. For eg: I want my span to be in black and <p> to be in red. I used to do this by $(this).html('my html here').css(styling here)
this is good in terms of performance - you create a string of the code you want to append and then you append it - causing a single change to the DOM - far better than multiple .append() functions which alter the DOM each time. I also agree with @Shree regarding inline styling - best if you an get into a habit of keeping it separate.
6

You can create an html element like this:

var p = $('<p>').html('Hello world');

This still not "exists" in your page, you need to append it to your selector using both append or appendTo (depending from the "point of view"):

$(this).append(p);

or

p.appendTo($(this));

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.