1

I want to add class on siblings of target Element in javascript. I have done this before using jquery which is pretty easy. But In my current organization they do not use jquery and I need to done with javascript and that is very difficult for me.

I have write some code that will attached a click function to an matched element but afterward I am not getting any login to how to make it happend. fiddle

var elements= document.getElementsByTagName('*'),i;
i=0;

while(elements[i]){
    if(elements[i].className=='c'){
        elements[i].addEventListener('click',function(){            
            this.jsSiblings().jsAddClass('newClass')
            })
        }
    i++
}


Array.prototype.jsSiblings= function(){

//code  
}

Array.prototype.jsAddClass=function(){

//code
}
cweiske
  • 30,033
  • 14
  • 133
  • 194
Jitender
  • 7,593
  • 30
  • 104
  • 210
  • Just a sidenote: The object returned by `getElementsByTagName()` is not an array, it's a [HTMLCollection](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection), and `this` in an event handler usually refers to the HTML element, to which the event has been atached to. – Teemu Jan 01 '15 at 19:35

1 Answers1

1

You can use the base function in JS to add a class, element.classList.add("anotherclass"); (from MDN) and here you will find out about siblings without jQuery : How to find all Siblings of currently selected object

Community
  • 1
  • 1
sodawillow
  • 12,497
  • 4
  • 34
  • 44
  • Can we do it with prototype methods – Jitender Jan 01 '15 at 19:44
  • @amit Why you assume JavaScript `Array` would be in the prototype chain of an HTML element? It is not. – Teemu Jan 01 '15 at 19:46
  • You will have to get help from someone else around, as I'm really not used to this way of doing. As for the array/collection, function `getElementsByTagName()` returns a `NodeList` according to the spec, which is not an array (http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-A6C9094). – sodawillow Jan 01 '15 at 19:47
  • @Teemu: I thought it is part of array. So now how do we attached proptotype chain in Html collection or html element – Jitender Jan 01 '15 at 19:50