Grant Smith
Grant Smith

Reputation: 351

JavaScript only targets first element on page

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>

Becomes

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

My script:

// 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?

Upvotes: 1

Views: 1331

Answers (2)

Mamun
Mamun

Reputation: 68933

querySelector() returns only the first matched element. To get all the elements from the page you have to use querySelectorAll(). Then loop through all the element for the change to make:

"use strict";

var anchor = document.querySelectorAll(".button");
anchor.forEach(function(a){
  a.innerHTML = "<span>" + a.textContent + "</span>";
});
span{
  color: green;
}
<a class="button" href="#">Home</a><br>
<a class="button" href="#">About Us</a><br>
<a class="button" href="#">Read More</a>

Upvotes: 2

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

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>

Upvotes: 2

Related Questions