如何 select optgroup 中的所有选项?
How to select all options within an optgroup?
我想知道 select 单个选项组中所有选项的最简单方法是什么?
我的理解是 optgroup 标签本身不能 selected,所以我当前的实现有一个选项元素紧跟在每个 optgroup 标签之后,上面写着类似“此 optgroup 中的所有选项”之类的内容。当此“全部”选项为 selected 时,我能够检测到该事件,但在那之后我迷路了。这是低头的正确途径,还是我让它变得比需要的更难?
使用属性选择器:
'[attribute name = "value"]'
const groupA = document.querySelector('[label="A"]');
/*
Using .querySelectorAll() to collect all of optgroup A options into a NodeList
*/
const groupA = document.querySelector('[label="A"]');
const allOptA = groupA.querySelectorAll('option');
allOptA.forEach(opt => opt.style.color = 'tomato')
/*
Using .children and spead operator [...x] to get all options from optgroup B
into an Array
*/
const groupB = document.querySelector('[label="B"]');
const allOptB = groupB.children;
[...allOptB].forEach(opt => opt.style.color = 'lime');
// Gather all optgroups into an Array
const allGroups = [...document.querySelectorAll('optgroup')];
// Gather each optgroups' options into a sub-array
const allOpts = allGroups.flatMap(grp => [grp.querySelectorAll('option')]);
// Get the value of the first optgroup third option
console.log(allOpts[0][2].value);
<select>
<optgroup label='A'>
<option value='0'>0</option>
<option value='2'>2</option>
<option value='4'>4</option>
</optgroup>
<optgroup label='B'>
<option value='1'>1</option>
<option value='3'>3</option>
<option value='5'>5</option>
</optgroup>
</select>
我想知道 select 单个选项组中所有选项的最简单方法是什么?
我的理解是 optgroup 标签本身不能 selected,所以我当前的实现有一个选项元素紧跟在每个 optgroup 标签之后,上面写着类似“此 optgroup 中的所有选项”之类的内容。当此“全部”选项为 selected 时,我能够检测到该事件,但在那之后我迷路了。这是低头的正确途径,还是我让它变得比需要的更难?
使用属性选择器:
'[attribute name = "value"]'
const groupA = document.querySelector('[label="A"]');
/*
Using .querySelectorAll() to collect all of optgroup A options into a NodeList
*/
const groupA = document.querySelector('[label="A"]');
const allOptA = groupA.querySelectorAll('option');
allOptA.forEach(opt => opt.style.color = 'tomato')
/*
Using .children and spead operator [...x] to get all options from optgroup B
into an Array
*/
const groupB = document.querySelector('[label="B"]');
const allOptB = groupB.children;
[...allOptB].forEach(opt => opt.style.color = 'lime');
// Gather all optgroups into an Array
const allGroups = [...document.querySelectorAll('optgroup')];
// Gather each optgroups' options into a sub-array
const allOpts = allGroups.flatMap(grp => [grp.querySelectorAll('option')]);
// Get the value of the first optgroup third option
console.log(allOpts[0][2].value);
<select>
<optgroup label='A'>
<option value='0'>0</option>
<option value='2'>2</option>
<option value='4'>4</option>
</optgroup>
<optgroup label='B'>
<option value='1'>1</option>
<option value='3'>3</option>
<option value='5'>5</option>
</optgroup>
</select>