jennifer
jennifer

Reputation: 301

get element by class for chrome

I am trying to add this code into a chrome extension to alert me when a chatbox is available. Its in a div with class name shoutbox as of now it doesnt work.

function Detection(){
    if(document.getElementsByClassName("shoutbox")!=null){
      alert('Chat is available.')
    }
}

Detection();

Updated Code: the page loads and the alert dialog never appears.

function Detection(){
    if(document.getElementsByClassName("shoutbox").length > 0){
        alert('Chat is available.')
    }
}

window.onload = Detection;

Upvotes: 5

Views: 10405

Answers (3)

serg
serg

Reputation: 111265

If chatbox is not on the page since the beginning and is added later (it is simple to check - just view the page source), you can monitor DOMSubtreeModified event which would fire whenever any modification is done to the page DOM:

document.addEventListener('DOMSubtreeModified', function(e) {
    if(document.getElementsByClassName("shoutbox").length > 0){
        alert('Chat is available.')
    }
});

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227260

document.getElementsByClassName("shoutbox") returns an array of elements, and returns a blank array if it doesn't find anything. To see if the elements exist, check the length of the array.

if(document.getElementsByClassName("shoutbox").length > 0){

Upvotes: 0

Jim Blackler
Jim Blackler

Reputation: 23169

== null won't detect an empty array (no results). You could write

if(document.getElementsByClassName("shoutbox").length > 0){
  alert('Chat is available.')
}

Upvotes: 5

Related Questions