querySelector、querySelectorAll选择元素示例



*.important {color:red;}  类名为important


HTML 5增加了一项新功能是自定义数据属性,也就是 data-* 自定义属性。在HTML5中我们可以使用以 data- 为前缀来设置我们需要的自定义属性,
来进行一些数据的存放。当然高级浏览器下可通过脚本进行定义和数据存取。在项目实践中非常有用。
关于data-属性选择器
在实际开发时,您可能会发现它很有用,你可以根据自定义的 data- 属性选择相关的元素。例如使用querySelectorAll选择元素:

// 选择所有包含 'data-tea' 属性的元素
document.querySelectorAll('[data-tea]');
 
// 选择所有包含 'data-text-colour' 属性值为red的元素
document.querySelectorAll('[data-text-colour="red"]');


document.querySelector('#myheader') //returns the element with ID="myheader"
document.querySelector('p.description') //returns the P with class="description" element

document.querySelector('#content img:nth-of-type(1)') //returns the 1st image within container "#content"
document.querySelector('#myform input[type="radio"]:checked') //selects the checked radio button within "#myform"

document.querySelector('form[action="feedback.php"]') // references form with action="feedback.php"
document.querySelector('img[src^="http"]') // selects 1st image with src beginning with "http"
document.querySelector('img[src$="blank.gif"]') // selects 1st image with src ending in "blank.gif"

document.querySelector('#biography, #gallery') //returns either element "#biography" or "#gallery", depending on which one is found first within document tree


document.querySelectorAll('.mygroup') //returns all elements with class="mygroup"
document.querySelectorAll('option[selected="selected"]') //returns the default selected option within each SELECT menu
document.querySelectorAll('#mytable tr>td:nth-of-type(1)') //returns the first cell within each table row of "mytable"

document.querySelectorAll('a[src^="http"]') // selects all links with href beginning with "http"
document.querySelectorAll('a[href*="javascriptkit"]') // selects all links with href containing sub string 'javascriptkit'

document.querySelectorAll('#biography, #gallery') //returns both elements "#biography" and "#gallery" (inclusive)


  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值