本教程操作环境:windows7系统、javascript1.8.5版、dell g3电脑。
javascript有选择器。
javascript最常用于获取或修改html元素的内容或值以及应用某些效果。
为此,您必须首先找到元素。而javascript选择器就是用于匹配元素的,查找方法:
通过id查找html元素
通过标签名称查找html元素
通过类名称查找html元素
通过css选择器查找html元素
通过html对象集合查找html元素
常用js选择器有:getelementbyid()、getelementsbyname()、getelementsbytagname()、getelementsbyclassname()、queryselector()、queryselectorall()。
按id查找html元素
您可以使用getelementbyid()方法根据元素的唯一id选择元素。
这是在dom树中找到html元素的最简单方法。
以下示例选择一个具有id属性id=msg的元素:
var x = document.getelementbyid("msg");
如果找到该元素,则该方法将把该元素作为对象返回。
如果找不到该元素,则myelement将包含null。
通过标签名称查找html元素
您还可以使用getelementsbytagname()方法通过标记名称选择html元素。
此方法返回具有指定标签名称的文档中所有元素的类似数组的列表。
示例:选择所有<p>元素:
var x = document.getelementsbytagname("p");
通过类名称查找html元素
您可以使用该getelementsbyclassname()方法选择具有特定类名称的所有元素。
此方法返回具有指定类名的文档中所有元素的类似数组的列表。
此示例返回所有带有class="demo"的元素的列表:
var x = document.getelementsbyclassname("demo");
通过css选择器查找html元素
您可以使用该queryselectorall()方法来选择与指定的css选择器匹配的元素(id,类,类型等)。
此方法返回与指定选择器匹配的所有元素的类似数组的列表。
css选择器提供了一种非常强大有效的选择文档中html元素的方法。
var x = document.queryselectorall("div");
通过html对象集合查找html元素
html文档中最顶层的元素可以直接用作文档属性。
例如,可以使用属性访问<html>元素document.documentelement。
所述元件可以与被访问document.body属性。
var html = document.documentelement;var body = document.body;
注意:如果document.body在标记之前使用(例如,在93f0f5c25f18dab9d176bd4f6de5d30e内),它将返回null而不是body元素。
也可以访问以下html对象(和对象集合):
属性描述
document.anchors 返回所有具有名称属性的3499910bf9dac5ae3c52d5ede7383485元素
document.applets 返回所有082dedeb30a00d0e6e2cdb74a392fac3元素(在html5中已弃用)
document.baseuri 返回文档的绝对基本uri
document.body 返回元素
document.cookie 返回文档的cookie
document.doctype 返回文档的文档类型
document.documentelement 返回100db36a723c770d327fc0aef2ce13b1元素
document.documentmode 返回浏览器使用的模式
document.documenturi 返回文档的uri
document.domain 返回文档服务器的域名
document.domconfig 已废弃;返回dom配置
document.embeds 返回所有d8e2720730be5ddc9c2a3782839e8eb6元素
document.forms 返回所有ff9c23ada1bcecdd1a0fb5d5a0f18437元素
document.head 返回93f0f5c25f18dab9d176bd4f6de5d30e元素
document.images 返回所有a1f02c36ba31691bcfe87b2722de723b元素
document.implementation 返回dom实现
document.inputencoding 返回文档的编码(字符集)
document.lastmodified 返回文档更新的日期和时间
document.links 返回所有具有href属性的03fc64e1e502d5ba947b3a9af06d2d2a和3499910bf9dac5ae3c52d5ede7383485元素
document.readystate 返回文档的(加载中)状态
document.referrer 返回引用者的uri(链接文档)
document.scripts 返回所有3f1c4e4b6b16bbbd69b2ee476dc4f83a元素
document.stricterrorchecking 返回是否强制执行错误检查
document.title 返回b2386ffb911b14667cb8f0f91ea547a7元素
document.url 返回文档的完整url
【相关推荐:javascript学习教程】
以上就是javascript有选择器吗的详细内容。
