Skip to content

用原生JS获取元素的另一种方法 #3

@52admln

Description

@52admln

目前比较流行的用原生JS获取元素的方法
document.querySelector() // 返回一个元素

document.querySelectorAll() // 返回元素集合

使用案例:
获取ID为ele的元素,则
document.querySelector("#ele")
获取Class为item的所有元素,则
document.querySelectorAll(".item")

括号当中使用CSS选择器即可获取到元素

Tips:
可以将第一个封装成
function $(ele) { return document.querySelector(ele); }
使用
$("#ele")
就可以啦

浏览器兼容:>=IE8及Chrome,Safari,Firefox等主流浏览器

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions