Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
like image 379
jennifer Avatar asked Apr 21 '11 16:04

jennifer


People also ask

How do I find an element by its class?

The syntax is as follows:getElementsByClassName(name); Here “name” is the class name you are looking to find and “elements” is a variable that would contain the array of elements.

How do I find the class name of an element in Chrome?

If you are using Chrome, open up the inspector, inspect the element you want to click. Right click over the element in the Elements panel and then scroll down to Copy > Copy JS Path and then paste the result. It should be a querySelector for that specific element.

What does getElementsByClassName () function return?

The getElementsByClassName() method returns a collection of elements with a specified class name(s). The getElementsByClassName() method returns an HTMLCollection.

How do I view elements in Chrome?

Method 1: Inspect Element Using Chrome Developer ToolsAt the top right corner, click on three vertical dots. From the drop-down menu, click on More tools -> Developer Tools. macOS users can use the shortcut – command + option + C and Windows users can use Control + Shift + C.


1 Answers

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

if(document.getElementsByClassName("shoutbox").length > 0){
  alert('Chat is available.')
}
like image 87
Jim Blackler Avatar answered Sep 29 '22 09:09

Jim Blackler