Skip to content Skip to sidebar Skip to footer

How To Chain Selectors In Javascript Without JQuery

While trying to manipulate the layout of external sites I am often forced to use a chain of selectors to target the specific element I want. The first time I encountered this I was

Solution 1:

Enter document.querySelectorAll.

It's what jQuery uses internally for browsers that support it. The syntax is the same as in jQuery (Sizzle) selectors, see Selectors API.


Solution 2:

This isn't pretty..

For each nested/chained element you can get its children via childNodes property. And then let the looping commence. :/ You'd then have to recursively loop through all children and children's children, and so on, until you find the appropriately matched element(s).

Updated:

To check for part of class name, you can do something like this:

if (element.className.indexOf('myClass') >= 0) {
   // found it!
}

Solution 3:

If you want to avoid jQuery and only use complex CSS selectors then the SizzleJS library might be what you need. It's a lot easier than doing it yourself every time you're looking for a DOM element!


Solution 4:

function selectors(){
      var temp= [];      //array for storing multiple id selectors.
      for(var i = 0;i<arguments.length;i++){
      if(typeof arguments[i] === 'string')
      temp.push(document.getElementById(arguments[i])); 
            }

          return temp; //for chanining
      },

 now call the function as many time as you want like
selectors('p').selectors('anyid') 

Post a Comment for "How To Chain Selectors In Javascript Without JQuery"