Javascript: how do i check if node has children

badtz7229
badtz7229 used Ask the Experts™
on
I have the following XML and I want a function that will throw an error whenever there's an instance of an Empty <Name> (or where <Name> has no children). How do I capture that?

<root>
	<Person>
		<Name/>
	</Person>
	<Person>
		<Name>
			<fname>babe</fname>
			<lname>ruth</lname>
		</Name>
	</Person>
</root>

Open in new window

i have the following code:
var nsPerson = dom.SelectNode(dom.Root, "Person/Name");
if (nsPerson)
{
	for (var i=0; i < nsPerson.Count; i++)	
	{
		var nPerson =  nsPerson.GetItem(i);
		if (!nPerson)
		{
		  //throw "Empty Person.";
				
		}
	}
}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
With document.getElementById("yourItem").parentNode; see http://www.w3schools.com/jsref/prop_node_parentnode.asp.
Scott FellDeveloper & EE Moderator
Fellow 2018
Most Valuable Expert 2013

Commented:
Sar1973 how would you update his code using your solution?
i answered my own question.

var nsPerson = dom.SelectNode(dom.Root, "Person/Name");
if (nsPerson)
{
      for (var i=0; i < nsPerson.Count; i++)      
      {
            var nPerson =  nsPerson.GetItem(i);
            if (nPerson)
            {
                           var hasChildren = nPerson.SelectSingle('*');
                           if (!hasChildren)
                                    throw "Empty, try again.";                  
                        
            }
      }
}

Author

Commented:
this worked

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial