6

I am new to jQuery. I want to write the following HTML (along with the classes) using jQuery. How can I do this?

<div class="phnbr">
  <div class="phtext">hi how are you, <a target="_blank" href="http://www.xyz.com">click here.</a>
  </div>
</div>
1
  • Why do you want to do this in jQuery? Commented Apr 8, 2011 at 9:20

3 Answers 3

16
$('<div>').addClass('phnbr').append($('<div>').addClass('phtext').append('hi how are you, ').append($('<a>').attr({ target: '_blank', href: 'http://www.xyc.com'}).text('click here.')));
Sign up to request clarification or add additional context in comments.

Comments

7
$('<div class="phnbr"> \
  <div class="phtext">hi how are you, <a target="_blank" href="http://www.xyz.com">click here.</a> \
  </div> \
</div>'); // bang done!

3 Comments

Not the best way to represent jQuery imho ;)
@NKCSS, This one would be faster that your solution. Moreover, no need of long chained statements. Moreover, shows the power of JQuery to a beginner. etc etc
I like this answer as it is quite readable how the HTML structure is. Creating objects for each tag and using append and appendTo is already confusing with 5+ tags in my opinion.
5

Well you can just use append() or the other DOM Insertion Functions

$(document.body).append('<div class="phnbr"><div class="phtext">hi how are you, <a target="_blank" href="http://www.xyz.com">click here.</a></div></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.