Reputation: 3462
Basically, i try to append a list using jquery. Each element in this list is connected to a different link. This is what i done
for (i=0; i <data.length ; i++ ){
var a = $('<a />');
a.attr('href','https://example.com/browse/' + data[i].key);
a.text(data[i].name);
$("#list-of-project ul").append("<li>").append(a).append("</li>");
}
"data" here is an JSON array i get from REST having key and name attribute. However, using this , i got output like this unwanted result. The element not at the same line with the list points. I want the text to be at the same line with the list points. Any help??
Upvotes: 1
Views: 2117
Reputation: 1885
<input type="test" id="inputName" />
<button id="btnName">Click me!</button>
<ul class="justList"></ul>
$('#btnName').click(function(){
var text = $('#inputName').val();
if(text.length){
$('<li />', {html: text}).appendTo('ul.justList')
}
});
Upvotes: 0
Reputation: 318342
You can't append partial elements, like just opening and closing LI tags.
Create the LI element first, then append the anchor to it, then append it to the UL
for (i=0; i <data.length ; i++ ){
var a = $('<a />', {
href : 'https://example.com/browse/' + data[i].key,
text : data[i].name
});
var li = $('<li />');
$("#list-of-project ul").append( li.append(a) );
}
Note that if data
has many indices, you should do the appending outside the loop, and append all the elements at once
Upvotes: 1
Reputation: 35
for (i=0; i <data.length ; i++ ){
var a = $('<a />');
a.attr('href','https://example.com/browse/' + data[i].key);
a.text(data[i].name);
var li ="<li>"+a+"</li>"
$("#list-of-project ul").append( li );
}
Upvotes: 2
Reputation: 6780
You don't need to append the open and closing tags like you are doing, simple append the a
to the li
, then append the li
to the ul
...
for (i=0; i <data.length ; i++ ) {
var a = $('<a />');
a.attr('href','https://example.com/browse/' + data[i].key);
a.text(data[i].name);
var li = $('<li/>');
li.append(a);
$('#list-of-project ul').append(li);
}
Upvotes: 0