user3201732
user3201732

Reputation: 41

Selecting and modifying DOM elements

How do I select DOM elements in JS? What is the equivalent for jQuery's $ selection syntax?

For example I have a <div> element:

<div id="idDiv">Div Element</div>

Now I want to apply addClass("ClassName") jQuery function on div. I can do it with jQuery with the following way:

$("#idDiv").addClass("ClassName") or jQuery("#idDiv").addClass("ClassName")

How can I do this with vanilla JS?

Upvotes: 2

Views: 111

Answers (3)

Ram
Ram

Reputation: 144659

You can use the classList API:

// Adding classes
document.getElementById('idDiv').classList.add('foo');
// Toggling classes
document.getElementById('idDiv').classList.toggle('foo');
// Removing classes
document.getElementById('idDiv').classList.remove('bar');

Please note that IE9 and below do not support the API, for supporting those browsers you can use a shim, MDN has one.

An experimental solution:

function jFoo(selector) {
    return {
        elems: [].slice.call(document.querySelectorAll(selector)),
        _handleClass: function (cls, m) {
            var len = this.elems.length,
                cls = cls.trim().split(/\s/),
                clen = cls.length;
            for (var i = 0; i < len; i++) {
                for (var j = 0; j < clen; j++)
                this.elems[i].classList[m](cls[j]);
            }
            return this;
        },
        addClass: function (cls) {
           return this._handleClass(cls, 'add');
        },
        toggleClass: function (cls) {
           return this._handleClass(cls, 'toggle');
        },
        removeClass: function (cls) {
           return this._handleClass(cls, 'remove');
        },
    }
}

jFoo('selector').toggleClass('foo bar')
                .addClass('barz fool')
                .removeClass('foo'); 

Upvotes: 5

Shashank
Shashank

Reputation: 399

You can get element by javascript in following way:

    var getelem = document.getElementById("idDiv");

    getelem.setAttribute("class", "active");

Upvotes: 1

gauravmuk
gauravmuk

Reputation: 1616

Another way of adding class using javascript:

document.getElementById("idDiv").className += " ClassName";

Upvotes: 0

Related Questions