返回元素的选择器...登陆

元素的选择器

飘云2018-12-30 11:59:10232

    //根据name标签名和name属性选择元素的快捷方式:仅适用于极少的几个,这是历史原因造成的

    // images: 所有的<img>元素 图像,数组, 有三种访问方式

    document.images[0].style.width = '200px';       // 1.标签索引

    document.images['pic'].style.width = '200px';   // 2.name 属性

    document.images.pic.style.width = '300px';      // 3.将name视为元素对象的属性进行访问


    // forms: 所有的<forms>元素 表单,数组

    document.forms[0].style.backgroundColor = 'lightgreen';

    document.forms['register'].style.backgroundColor = 'lightblue';

    document.forms.register.style.backgroundColor = 'red';

    document.forms.item(0).style.backgroundColor = 'lightgreen';  // 类数组可用item()方法获取某个元素


    //a 链接: 所有的<a>元素,NodeList 数组

    document.links[0].style.backgroundColor = 'yellow';

    document.links['php'].style.backgroundColor = 'red';

    document.links.php.style.backgroundColor = 'green';


    // body: <body>元素,总有定义,只有一个

    document.body.style.backgroundColor = 'wheat';


    // head: <head>元素,总有定义,不写会自动添加,只有一个

    let style = document.createElement('style');

    document.head.appendChild(style);

    // .red 获取 class="red"的元素,其实js也支持使用css选择器获取元素

    let lists = document.querySelectorAll('li');

    console.log(lists);     //返回节点列表数组,里面每个元素对应一个元素

    //可以使用

    lists[0].style.backgroundColor = 'coral';

    lists.item(1).style.backgroundColor = 'lightblue';


    //该方法还可以在元素上调用,这也根据标签和class类名获取元素是一样的

    let ul = document.querySelector('#ul'); // 获取满足条件的第一个元素

    console.log(ul);    // 只返回ul列表元素以及内部子元素

    let li = ul.querySelectorAll('.green');

    for (let i = 0; i < li.length; i++) {

        li[i].style.backgroundColor = 'green';

    }


最新手记推荐

• 用composer安装thinkphp框架的步骤• 省市区接口说明• 用thinkphp,后台新增栏目• 管理员添加编辑删除• 管理员添加编辑删除

全部回复(0)我要回复

暂无评论~
  • 取消回复发送