dynamically create element using jquery

DrWooolie picture DrWooolie · Feb 6, 2013 · Viewed 28.6k times · Source

I am trying to create element using jquery. When i click on a link, i want to create an element "p", give it some text, and then put it in one of my divs. Also, i want to check which link is clicked on, so i can put the created "p" in the right div. Any solutions on where i am doing it wrong?

Javascript/Jquery

$(document).ready(function () {

function createElement() {
  var a = $("#menu").find('a').each(function(){
    if(a == "l1"){
    var text = $(document.createElement('p');
    $('p').text("Hej");
    $("#contentl1").append("text");
    }
  });
}

$("#menu").find('a').each(function () {
    $(this).click(function () {
        createElement();
    });
});

createElement();

});

HTML

      <html>

<head>
<title>Inl1-1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="style-1.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="Uppg1.js"></script>
</head>

<body>

<ul class="meny" id="menu">
<li><a href="#" id="l1">Utvärdering/Feedback</a></li>
<li><a href="#" id="l2">Kontakt</a></li>
<li><a href="#" id="l3">Öppettider</a></li>
<li><a href="#" id="l4">Om Asperöd</a></li>
</ul>

<div id="contentl1">

</div>

<div id="contentl2">

</div>

<div id="contentl3">

</div>

<div id="contentl4">

</div>

</body>

</html>

Answer

VisioN picture VisioN · Feb 6, 2013

Here is the best way to add new <p> element with text "Hej" to #contentl1 using jQuery:

$("<p />", { text: "Hej" }).appendTo("#contentl1");