Get first
  • WITHOUT jquery
  • 后端 未结 7 1095
    爱一瞬间的悲伤
    爱一瞬间的悲伤 2020-12-19 08:13

    This may have been asked, but scrolling through about 40+ search results reveals only the jQuery solution. Let\'s say I want to get the first item in an unordered list and a

    相关标签:
    7条回答
    • 2020-12-19 08:44

      Using the basic DOM operations:

      var ul = document.getElementById('id of ul');
      var child = ul.childNodes[0];
      
      0 讨论(0)
    • 2020-12-19 08:49

      Also consider sizzle, depending on your needs. Smaller than jQuery, but handles all your selector normalization.

      0 讨论(0)
    • 2020-12-19 08:51
      document
          .getElementsByTagName("ul")[0]
          .getElementsByTagName("li")[0]
          .style.color = "blue";
      
      0 讨论(0)
    • 2020-12-19 08:53

      If you need to change style only, use CSS :first-child

      ul > li:first-child {
          color: blue;
      }
      

      works even in IE7 http://caniuse.com/#feat=css-sel2

      http://jsfiddle.net/Tymek/trxe3/

      0 讨论(0)
    • 2020-12-19 08:54

      Since the only valid child of <ul> is <li>, you can do this:

      var firstLI = document.getElementsByTagName('ul')[0].children[0];
      
      0 讨论(0)
    • 2020-12-19 08:55

      You can use querySelector (IE7 and lower not supported):

      document.querySelector("ul > li")
      

      Or querySelectorAll:

      document.querySelectorAll("ul > li")[0]
      

      Or getElementsByTagName:

      document.getElementsByTagName("ul")[0]
              .getElementsByTagName("li")[0]
      

      The best way to change style IMO is to set a class. You do this by setting (or expanding) the .className property of the resulting element.

      Otherwise you can set the individual styles using the .style property.


      update

      As @Randy Hall pointed out, perhaps you wanted to first li of all ul elements. In that case, I would use querySelectorAll like this:

      document.querySelectorAll("ul > li:first-child")
      

      Then iterate the result to set the style.


      To use getElementsByTagName, you could do this:

      var uls = document.getElementsByTagName("ul");
      
      var lis = [].map.call(uls, function(ul) {
          return ul.children[0];
      });
      

      You'll need an Array.prototype.map() shim for IE8 and lower.

      0 讨论(0)
    提交回复
    热议问题