Search code examples
javascriptattributesmousehover

Does the hasAttribute function allow the ID or Name of the attribute?


I am working on a script for hovering. Basically I create a div that gets put in a chat box container on hovering over a specific item (in this case, a button) and displays some text in the chat box. After you remove your hover, the text will disappear.

I haven't quite got to the disappear part yet, but that's not quite what I need help with. I'm using the hasAttribute function to identify my newly created Div. The problem I"m running into is, that if I hover over my button object, I get "its false" when I set hasAttribute("hovertext"), but if I set hasAttribute to "Class", I get "its true".

My program uses multiple created / instance divs and all of them have classes. So just saying "class" would not really target specifically "hovertext" divs.

Does the hasAttribute have something along the lines class naming? Like this: hasAttribute("class:hovertext")?enter image description here

function hoverMessage(message) {
    var chatbox = dom.el("chatbox");
    var div = document.createElement("div");
    // chatbox.appendChild(div).textContent = message;
    chatbox.appendChild(div).innerHTML = message;
    chatbox.setAttribute("class", "chatboxtext");
    div.setAttribute("class", "hovertext");

    if (div.hasAttribute("class"))
    {
        console.log("its true");

    }
    else {
        console.log("its false");
        console.log(div);
    }
    chatbox.scrollTop = chatbox.scrollHeight;   
};

Solution

  • In your case, in order to test if the element has a specified class you can use:

    classList.contains( String ): Checks if specified class value exists in class attribute of the element.

    var retVal = document.querySelector('p').classList.contains('hovertext');
    console.log(retVal);
    <p class="class1 class2 hovertext class3"></p>