Search code examples
javascriptuserscripts

Userscripts, going through elements and testing attributes


I'm kinda new to Userscripts and JavaScript in general, and I'm pretty lost.

Basically what I want to do is go through elements I got by using getElementsByClassName, get the data in the "name" attribute, see if it contains something and if so, change the class name to something else.

In pseudo-ish-code:

items = getElementsByClassName("item1");

for each item in items {
    if(item.attribute("name").contains("Hi"))
        item.attribute("class") = "item2";
}

If someone could give me some tips on how I could do this, that'd be awesome.


Solution

  • Try this:

    // get all items with class 'item1'
    var items = document.querySelectorAll('.item1');
    var length = items.length;
    for (var i = 0; i < length; i++) {
        // save reference to current item
        var item = items[i];
        // check if name contains 'Hi'
        if (item.getAttribute('name').indexOf('Hi') !== -1) {
            // update class
            item.className += ' item2';
        }
    }
    

    Demo: http://jsfiddle.net/vpetrychuk/9zBnn