#22 获取子元素属性


  • 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)
    })
    }


  • 0

    @陈小俊 补充一下,普通对象应该是不能用for of遍历的。因为dom nodelist 是类数组对象所以才能用for of进行遍历。


  • 0

    请问,我应该如何测试呢,就是在本地能够运行,看到效果。@陈小俊


登录后回复
 

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