admin管理员组

文章数量:1431918

I have a tree view and a delete button on the webpage. The tree view loads with parent nodes and child nodes. If I click on delete after selecting a parent node with child nodes, it should give me a message provided below accordingly with a confirmation box.

Right now, when I select a parent node without any child nodes it gives me the following message: ""The element has at least one child.". When it should be giving me this message: "The element has no children."

Code:

function check() {
    var treeViewData = window["<%=nav_tree_items.ClientID%>" + "_Data"];
    var selectedNode = document.getElementById(treeViewData.selectedNodeID.value);

    var hasChilds = selectedNode.hasChildNodes();

    if (hasChilds) {
        alert("The element has at least one child.");
    } else {
        alert("The element has no children.");
    }

Please help. Thank you and sorry if I may have caused confusion in my explanation

I have a tree view and a delete button on the webpage. The tree view loads with parent nodes and child nodes. If I click on delete after selecting a parent node with child nodes, it should give me a message provided below accordingly with a confirmation box.

Right now, when I select a parent node without any child nodes it gives me the following message: ""The element has at least one child.". When it should be giving me this message: "The element has no children."

Code:

function check() {
    var treeViewData = window["<%=nav_tree_items.ClientID%>" + "_Data"];
    var selectedNode = document.getElementById(treeViewData.selectedNodeID.value);

    var hasChilds = selectedNode.hasChildNodes();

    if (hasChilds) {
        alert("The element has at least one child.");
    } else {
        alert("The element has no children.");
    }

Please help. Thank you and sorry if I may have caused confusion in my explanation

Share Improve this question edited Dec 19, 2011 at 18:55 Pointy 414k62 gold badges595 silver badges629 bronze badges asked Dec 19, 2011 at 18:47 IshIsh 6715 gold badges21 silver badges37 bronze badges 3
  • 2 What makes you sure the element has no child nodes of any type? Remember that a stray newline in the HTML source can result in a text node being included in the DOM. – Pointy Commented Dec 19, 2011 at 18:57
  • I'd inspect the nodeType for each child. There's probably something there you didn't expect: w3/TR/REC-DOM-Level-1/level-one-core.html#ID-1950641247 – canon Commented Dec 19, 2011 at 19:03
  • How do I know which nodetype? IS there any way of checking that? – Ish Commented Dec 19, 2011 at 19:11
Add a ment  | 

1 Answer 1

Reset to default 4

Try checking

var hasChilds = selectedNode.children.length > 0;

This will check for elements instead of childNodes which will check for elements and text nodes, which can e from whitespace in your markup.

本文标签: javascriptHaschildnodes() does not workStack Overflow