JavaScript仅定位页面上的第一个元素 [英] JavaScript only targets first element on page

查看:42
本文介绍了JavaScript仅定位页面上的第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下脚本,该脚本试图以 .button 类为目标的任何链接,以在文本元素周围添加< span> 标记.例如:

I have the following script which I am trying to target any link with a class of .button to add a <span> tag around the text element. For example:

<a class="button" href="#">Read More</a>

成为

<a class="button" href="#"><span>Read More</span></a>

我的脚本:

// insert span into anchor
"use strict";

var anchor = document.querySelector(".button");
var html = anchor.innerHTML;

anchor.innerHTML = "<span>" + html + "</span>";

这有效,但仅在页面的第一个实例上可用吗?

This works, but only on the first instance of the page?

推荐答案

您应使用ALL选择器

You should loop through all the elements using the ALL selector querySelectorAll() like :

var anchors = document.querySelectorAll(".button");

for( var i=0;i<anchors.length;i++){
     anchors[i].innerHTML = "<span>" + anchors[i].innerHTML + "</span>";
}

var anchors = document.querySelectorAll(".button");

for (var i = 0; i < anchors.length; i++) {
  anchors[i].innerHTML = "<span>" + anchors[i].innerHTML + "</span>";
}

console.log(document.body.innerHTML);

<button class='button'>Read More</button>
<br>
<button class='button'>Read More</button>
<br>
<button class='button'>Read More</button>

这篇关于JavaScript仅定位页面上的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆