Why isn't the appendChild node not formatted by the class?

OK, I’ll work on this.

I deliberately avoided innerHtml because: 1) I heard there could be security issues, 2) I already knew how to do this, and 3) to learn something new!

I still don’t see how to link list with parent. So far:

function makeDropdown(parent, href, text) {
    var placeholder = document.getElementById('placeholder');
    var list = document.createElement('ul');
    list.id = ("dropdown1");
    list.className = ("dropdown-content");
    var item = document.createElement('li');
    var link = document.createElement('a');
    var textNode = document.createTextNode(text);

    link.appendChild(textNode);
    link.setAttribute('href', href);
    item.appendChild(link);
    parent.appendChild(item);
placeholder.parentNode.replaceChild(list, placeholder);
}

makeDropdown(list, '../index.html', 'Home');
makeDropdown(list, 'search.html', 'Search');

That list wasn’t supposed to be created within the function here, but passed to the function as the parent argument. Like


// Here we create the list element outside the function
var list = document.createElement('ul');

// Also, we're assigning the reference to the placeholder element
// here, so that we don't have to query the DOM more than once
var placeholder = document.getElementById('placeholder');

// Then we can append as many items to the list as we like
appendItem(list, '#link', 'Some text');
appendItem(list, '#other-link', 'Some other text');

// And finally, we replace the placeholder with the list
placeholder.parentNode.replaceChild(list, placeholder);

When passing the list reference to appendItem, it becomes available within the scope of the function as parent.

But that was just an idea really; there are of course other possible solutions. For example, you could return the li element you created within the function, and “manually” append it to the list outside of it. This might be slightly more verbose, but on the other hand it would be a pure function, i.e. without side effects: the function just gets some input and returns some output, without modifying anything outside its scope.

OK, now I got it to work! Thanks for all the tips.

var makeDropdown = function(){
    var list = document.createElement('ul');
    list.id = ("dropdown1");
    list.className = ("dropdown-content");
    var placeholder = document.getElementById('placeholder');
    makeDropdown(list, '../index.html', 'Home');
    makeDropdown(list, 'search.html', 'Search');
    placeholder.parentNode.replaceChild(list, placeholder);

function makeDropdown(parent, href, text) {
    var item = document.createElement('li');
    var link = document.createElement('a');
    var textNode = document.createTextNode(text);

    link.appendChild(textNode);
    link.setAttribute('href', href);
    item.appendChild(link);
    parent.appendChild(item);
    };
};

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.