Selecting list items by id without jquery

Viewed 101

I have a list in html of this type

<ul>
 <li id="1.1" fatherid="1"> ...</li>
 <li id="1.2" fatherid="1"> ...</li>
 <li id="1.3" fatherid="1"> ...</li>
 ...
</ul>

And I want to select all the items of the list with a given fatherid. For example I'd like to select all the items with "1" as fatherid, but I don't know how to do it. I tried with querySelectorAll and getElementById but it didn't work, and I prefer not to use jquery. Thanks for the answers.

2 Answers

You can use data-attributes (https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes) to store the fatherids (which is the recommended way to add custom attributes to html elements). You can then find the tags with a given fatherid using the [data-fatherid] selector.

  function getByFather(id) {
    return document.querySelectorAll(`[data-fatherid='${id}']`);
  }
  
  console.log([...getByFather(1)]);
  console.log([...getByFather(2)]);
<ul>
 <li id="1.1" data-fatherid="1">1.1</li>
 <li id="1.2" data-fatherid="1">1.2</li>
 <li id="1.3" data-fatherid="1">1.3</li>
 
 <li id="2.1" data-fatherid="2">2.1</li>
 <li id="2.2" data-fatherid="2">2.2</li>
</ul>

Since Document.querySelectorAll accepts a selector we can make use of the CSS attribute selector:

const r = document.querySelectorAll('li[fatherid="1"]');
console.log(Array.from(r));
<ul>
 <li id="1.1" fatherid="1"> ...</li>
 <li id="1.2" fatherid="1"> ...</li>
 <li id="1.3" fatherid="1"> ...</li>
</ul>

Related