1

I'm trying to come with a way to remove functionality on a tag. I'm used to jquery and the code would be something like this.

$(document).on("click",".goto-messages:not(done)", function(e){...
...$(".profile-messages").addClass("done");

I'm trying to achieve the same thing using javascript but I'm failing at adding class attribut. I'm also not sure how to add the argument to not fire a function e.g. ":not(done)"

            document.getElementsByTagName("td").onclick = function(){
                this.style.background = blue;
                this.class
            }

How do I achieve this result in javascript? I want to remove the functionality of the element that is clicked.

Also is the line "this.style.background = blue;" correct?

user1924247
  • 171
  • 3
  • 9

2 Answers2

1

You will want something like this (unless you provide some HTML), example uses element.classList which is not supported by all browsers. But you can use something like domtokenlist library which should give you good support across all browsers, or there are some RegEx's that can be found in Adding and Removing Classes, with simple cross-browser JavaScript. As for adding events cross browser, instead of using addEventListener, you can take a look at the following How to make this Javascript function work in IE Browser? or do a search on SO for addEvent.

HTML

<table>
    <theader>
        <tr>
            <th>Mesages A</th>
            <th>Mesages B</th>
        </tr>
    </theader>
    <tbody>
        <tr>
            <td class="profile-messages">Message1</td>
            <td class="profile-messages">Message2</td>
        </tr>
        <tr>
            <td class="profile-messages">Message3</td>
            <td class="profile-messages">Message4</td>
        </tr>
        <tr>
            <td class="profile-messages">Message5</td>
            <td class="profile-messages">Message6</td>
        </tr>
    </tbody>
</table>

CSS

.profile-messages {
    background-color: red;
}
.done {
    background-color: blue;
}

Javascript

document.addEventListener("click", function (evt) {
    if (evt.target.tagName.toUpperCase() === "TD" && evt.target.classList.contains("profile-messages")) {
        evt.target.classList.add("done");
    }
}, false);

On jsfiddle

Community
  • 1
  • 1
Xotic750
  • 22,914
  • 8
  • 57
  • 79
0

document.getElementsByTagName() returns a NodeList, you have to iterate it:

var nodes = document.getElementsByTagName("td");
for (var i=0, len = nodes.length; i<len; i++) {
  nodes.item(i).onclick = function () {
    // do something
  };
}

Use document.querySelectorAll() for a CSS-like selector:

var nodes = document.querySelectorAll(".goto-messages:not(.done)");
ComFreek
  • 29,044
  • 18
  • 104
  • 156