0

I'm trying to change all h1's background color to red for example.

At my popup.js that is linked to popup.html I've added this code:

chrome.tabs.executeScript(null,
      {code:"document.getElementsByTagName('h1').style.backgroundColor='red';"});

it works fine with document.body, but I have no idea how to make it works with getelementbytagname

Also I'd like to add some text in the h1 container.

Xan
  • 74,770
  • 16
  • 179
  • 206
michal
  • 35
  • 6

2 Answers2

0

getElementsByTagName('h1') returns multiple results: an HTMLCollection to be precise.

You can't set .style on the collection itself.

In recent Chrome versions (51+), you can loop through it with for..of:

let headers = document.getElementsByTagName('h1');
for (let header of headers) {
  header.style.backgroundColor = 'red';
}

To add text to the header node, you can use standard DOM manipulation methods, e.g. .appendChild():

header.appendChild(document.createTextNode("Boo!"));

Or, you could manipulate its .textContent.

As your code grows in complexity, you should put it in a dedicated .js file and call executeScript with file instead of code.

Xan
  • 74,770
  • 16
  • 179
  • 206
0

I've added something like this:

chrome.tabs.executeScript(null, {
    code: "for (var z=0; z < 7; z++) { var el = document.getElementsByTagName('h' + z); for (var i=0; i < el.length; i++) { el[i].style.color ='red'; el[i].innerHTML += '[H' + z + ']';} }" 

});

and it's finnaly works :) Now I need to check if var el exists so it won't be marked multipe times.

Xan
  • 74,770
  • 16
  • 179
  • 206
michal
  • 35
  • 6
  • Note: `innerHTML` manipulation [considered harmful](https://stackoverflow.com/questions/11515383/why-is-element-innerhtml-bad-code). – Xan Sep 18 '17 at 12:40
  • is there better way to achieve marking h1 tags on website? – michal Sep 18 '17 at 12:47