We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 30223
    • 1,010 Posts
    Mootools version distributed with modx.
    I’m trying to determine if a div has any children but I can’t work out how to determine if there are none.
    sample HTML:
    <div id="test">
    	<input type="text" name="myText[]" /><br />
    	<input type="text" name="myText[]" /><br />
    	<input type="text" name="myText[]" /><br />
    </div>
    

    Tried this:
    <script type="text/javascript">
    i = $$("div#test").getElements('input');
    a = $$("div#test").getElements('a'); //should be none
    alert(i.length) // output: 1 (expected 3)
    alert(a.length) //output: 1 (expected 0)
    </script>
    


    Any suggestions?
      • 10487 MODX Staff
      • 1,535 Posts
      It’s a difference in what $ and $$ return. $ returns a single element, $$ returns an array of elements. So, this would work:
      <script type="text/javascript">
      window.addEvent('domready', function() {
          i = $("test").getElements('input');
          a = $("test").getElements('a');
          alert(i.length); // (expected 3)
          alert(a.length); //(expected 0)
      });
      </script>

      Or, something like this would also work (would need some adjustment if it really needs to account for multiple elements wink):
      <script type="text/javascript">
      	window.addEvent('domready', function() {
      		var ic = 0;
      		var ac = 0;
      		$$("div[id=test]").each(function(el) {
      			ic = el.getElements('input');
      		});
      		$$("div[id=test]").each(function(el) {
      			ac = el.getElements('a');
      		});
      		alert(ic.length);
      		alert(ac.length);
      	});
      </script>
        Garry Nutting
        Senior Developer
        MODX, LLC

        Email: [email protected]
        Twitter: @garryn
        Web: modx.com
        • 30223
        • 1,010 Posts
        It’s a difference in what $ and $$ return. $ returns a single element, $$ returns an array of elements.
        Dumb... embarrassed Could have thought of that myself... Thanks!

        What puzzled me is that you can do things like:
        $$("div.testClass").getStyle('display');

        but clearly not
        $$("div.testClass").getElements('input');

        I’d find it logical that the latter would work in a similar way, combining results of all elements found.