I am trying to write a chrome extension to change all hrefs in a page using this code
var a = document.querySelector("a[href]");
a.href = "http://www.google.com";
But this code only fetches the first href but only if it is not embedded in another attribute(If the term is wrong I am meaning div, p, h etc.)
Could someone show me how to fetch all hrefs no matter what?
document.querySelector only returns the first element within the document, and so in this case you will want to use document.querySelectorAll which instead returns a list of all matching elements.
var elements = document.querySelectorAll('a');
for (var i = 0; i < elements.length; i++) {
elements[i].href = 'http://google.com';
}
but only if it is not embedded in another attribute(If the term is wrong I am meaning div, p, h etc.)
I believe you are talking about tags instead of attributes. To select all tags with the present of the href
attribute, do this:
var list = document.querySelectorAll("*[href]");
for(var i = 0; i < list.length; i++){
list[i].href = "http://www.google.com";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.