knot22 knot22 - 4 months ago 16
HTML Question

setting name of an HTML element using jQuery

Here is some code that is resulting in failure to set the class for each li in a group of li tags:



function pathContents(fileList)
{
var $list = $('<ul/>');
$.each(fileList, function (_, file) {
$('<li/>').prop('class', 'test123');
$('<li/>').text(file).appendTo($list);
});
return $list;
}





When I open the Inspector in Firefox, right click on one of the li's, and choose 'Show DOM Properties' the className property shows empty string:
enter image description here



Since there is a CSS rule for the class test123 that says to make the font blue, and the font is still black, it appears that this line of code is not assigning a class of 'test123' to the li tags. I have also tried
$('<li/>').attr('class', 'test123');
which has given the exact same result as when trying to use .prop(). Why aren't these working?

Answer

You should try using addClass() instead of prop()

https://api.jquery.com/addclass/

And you are creating two different list items and only appending one of them.

$('<li/>').prop('class', 'test123');
$('<li/>').text(file).appendTo($list);

You can save try

$('<li/>').addClass('test123').text(file).appendTo(list);