1

What to do if I have to insert some value on a page element of a new tab within a Chrome extension?

I am using:

document.getElementsByClassName("quotes").innerHTML = Quotes[x];

in newtab-script.js page but it is showing this error in the console:

Uncaught TypeError: Cannot set property 'innerHTML' of null

My page contains a div with a class named quotes but when I alert this:

document.getElementsByClassName("quotes")

The result is null.

My code is in the form:

window.onload = function abc (){ 
  alert(document.getElementById('a'));    
  document.getElementById('a').innerHTML ="ishaan"; 
}

I am importing my script file in a html page which overrides Google Chrome's new tab page. My script is on the script file.

jwpfox
  • 5,124
  • 11
  • 45
  • 42
Maverick
  • 41
  • 1
  • 11

2 Answers2

1

If there are multiple items having same class name

var quoteElems=document.getElementsByClassName('quotes')
for(var i=0;i<quoteElems.length;i++){
quoteElems[i].innerHTML=Quotes[x]
}

If there is single item having class 'quotes'

document.getElementsByClassName("quotes")[0].innerHTML = Quotes[x];

Deep 3015
  • 9,929
  • 5
  • 30
  • 54
  • there is one class only and it' s class is showing as null . Is these any other way to do this in extensions – Maverick Nov 04 '16 at 11:03
  • Use `alert(quoteElems.length)` to check required element is there or not. It will show the number of element containing class 'quotes' – Deep 3015 Nov 04 '16 at 14:56
  • My last snippet will work on single class if exists ,try it.Other wise you have to dynamically create it. – Deep 3015 Nov 04 '16 at 15:04
0

if you use jquery then do

 $(function(){
   $('.quotes').html(Quotes[x]);
 });
madalinivascu
  • 32,064
  • 4
  • 39
  • 55