Reputation: 5039
I'm currently working on a web component repeater, and I'm encountering an issue when I try to mix two repeater in the same element. My HTML is:
<company-repeat id="table">
<table class="selectable" description="Résultats de recherche">
<thead>
<tr>
<company-repeat id="table-metadata">
<th class="sorting" repeatable>${name}</th>
</company-repeat>
<th></th>
</tr>
</thead>
<tbody>
<tr repeatable>
<td>${id}</td>
<td>${name}</td>
<td>${surname}</td>
<td>${registered}</td>
<td><i aria-hidden="true" class="fa fa-download" title="Télécharger">D</i></td>
</tr>
</tbody>
</table>
</company-repeat>
What I would like to do is generating the thead dynamically according to a list I receive, but the issue is that my code take the first "repeatable" element it found (this.template = this.querySelector('[repeatable]');
). What I need right now is a selector to specify that I want the first element it found, only if it's not child of another company-repeat.
Is it doable only with a selector or do I have to retrieve them all, check if the element is child of another element and then only set it to my property?
Something like document.querySelector('!company-repeat > [repeatable]');
would be perfect, but I highly doubt it exist.
Upvotes: 2
Views: 2024
Reputation: 1462
There can be two approaches you can use. consider the example given in snippet where we want to find the first <p>
element which is not child of <li>
element
First approach is to find all <p>
which are not decedent of <li>
element and display first <p>
element
var allP = $(document).find('p:not(li p)');
console.log(allP[0]);
Second approach is to find all <p>
element ,iterate over all <p>
elements and return first <p>
element whos parent is not <li>
allP = $(document).find('p');
var correctP;
for(i=0;i<allP.length;i++){
if($(allP[i]).parents('li').length==0){
correctP = allP[i];
break;
}
}
console.log(correctP);
Please see the snippet for more details.
//Here we are printing first p element who's parent is not li
//first approach
var allP = $(document).find('p:not(li p)');
console.log(allP[0]);
//second approach
allP = $(document).find('p');
var correctP;
for(i=0;i<allP.length;i++){
if($(allP[i]).parents('li').length==0){
correctP = allP[i];
break;
}
}
console.log(correctP);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<p>Hello p1</p>
<li><p>Hello p2</p></li>
<li><p>Hello p3</p></li>
<p>Hello p4</p>
</ul>
Upvotes: 1
Reputation: 1075587
Is it doable only with a selector...
Sadly not, no. There's no "select X but only if X is not a descendant of Y". (One is tempted by the :not
pseudoclass, but it only allows simple selectors, not the compound kind we'd need for this.)
...or do I have to retrieve them all, check if the element is child of another element and then only set it to my property?
Yes, that's the approach you'll need to use.
Upvotes: 2