#22 获取子元素属性


  • 0

    const getChildAttributes = (dom, attrStr) => [...dom.children].map(x => x.getAttribute(attrStr))
    

    转数组map就行,楼上方法多用了一个私有变量


  • 0

    const getChildAttributes = (el, attr) => {
      let ret = [];
      for(let item of el.children) {
        item.getAttribute(attr) ? ret.push(item.getAttribute(attr)) : ret.push(null)
      }
      return ret
    }
    

  • 0

    使用childern获取子元素的时候报错了:
    Runtime Error
    Cannot read property 'children' of null;

    const getChildAttributes = (el,name)=>{
          let dom = document.getElementById(el);
          var arr = [];
          dom.children.map((item,index)=>{
            app.push(item.getAttribute(name))
          })
          return arr;
        };
    

  • 0

    const getChildAttributes = (el, propname) => [...el.children].map(d => d.getAttribute(propname))
    
    

  • 0

    const getChildAttributes = (el, attr) =>
    {
    let arr = [];
    el.children.forEach(node) {
    arr.push(node.getAttribute(attr));
    }
    return arr;
    }
    报错为:
    Compile Error
    Unexpected token, expected ; (4:28)
    啥意思?


  • 0

    const getChildAttributes = function(el, attr){
      let result = [...el.children].map((item) => {
        return item.getAttribute(attr);
      });
      return result;
    }
    // 当然也可以简写成一行(不是很推荐)
    const getChildAttributes = (el, attr) => [...el.children].map(item => item.getAttribute(attr) );
    

  • 0

    const getChildAttributes = (e,a)=>Array.from(e.children,(o)=>o.getAttribute(a));
    

    一行搞定


  • 0

    function getChildAttributes(element, attributeName) {
      var childs = Array.from(element.children)
    
      return childs.map(child => {
        if (child.hasAttribute(attributeName)) {
          return child.getAttribute(attributeName)
        } else {
          return null
        }
      })
    }
    

  • 0

    const getChildAttributes = (el, attr) => Array.from(el.childNodes).filter(e => e.nodeType === 1).map(e => e.getAttribute(attr));
    const getChildAttributes = (el, attr) => Array.from(el.children).map(e => e.getAttribute(attr));
    const getChildAttributes = (el, attr) => Array.prototype.map.call(el.children,e => e.getAttribute(attr));
    const getChildAttributes = (el, attr) => [...el.children].map(e => e.getAttribute(attr));
    

  • 0

    const getChildAttributes = (dom, attr) => {
      dom = dom.children
      if (dom.length === 1) {
        return dom[0].getAttribute(attr)
      } else {
        return Array.from(dom).map((item) => item.getAttribute(attr))
      }
    }
    

  • 0

    const getChildAttributes = (dom, attr) => Array.from(dom.children).map((item) => item.getAttribute(attr))
    

  • 0

    const getChildAttributes = (el, attr) => {
    return [... el.children].map(item => {
    return item.getAttribute(attr)
    })
    }


登录后回复
 

与 ScriptOJ 的连接断开,我们正在尝试重连,请耐心等待