Like javascript selector chains without jQuery

When I try to manipulate the layout of external sites, I often have to use a chain of selectors to target the specific element that I want. The first time I came across this, I was offered a jQuery solution, and getting the results is very easy. I would rather not rely on jQuery and would like to know as much as possible in standard Javascript. Here is a jQuery 'chain' example -

$('div[id="entry"] > p[class="header"] > span[id="title"] > div[class*="entry"] > p[class="title"] > a[class*="target"]').. etc 

Let's say the HTML structure is roughly equal

 <div id="entry"> <p class="primary"> <p class="header"> <span class="side"> <span id="title"> <div class="secondary entry"> <p class="return"> <p class="title"> <a class="img"> <a class="mytargetelement"> 

So how is this possible normal? Thanks.

+4
source share
4 answers

Type document.querySelectorAll .

This is what jQuery uses internally for browsers that support it. The syntax is the same as in jQuery (Sizzle) selectors, see APIs> .

+8
source

It's not beautiful..

For each nested / related element, you can get your children through the childNodes property. And then let the cycle begin.: / Then you have to recursively scroll through all the child and child children, etc. Until you find the appropriate matching item (s).

Updated :

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

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

If you want to avoid jQuery and use only complex CSS selectors, then the SizzleJS library may be what you need. This is much easier than doing it every time you look for a DOM element!

+2
source
 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') 
+1
source

All Articles