0

GOAL: Looking to create a vanilla JavaScript reference to an item with a class and a specific value.

What I'm trying to say in English: Select the item from a group of matching items where the value == "home".

My attempted selection:

const v = "home";

const pickedSection = document.querySelectorAll('.bonus-section').value == v;

console.log('picked Section: ', pickedSection)

HTML

<ul>
   <li class="bonus-section" value="home">home</li>
   <li class="bonus-section" value="auto">auto</li>
   <li class="bonus-section" value="life">life</li>
</ul>

(There will only be one returned nodeItem.)

Current console output: picked Section: – false

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Michael Martell
  • 141
  • 2
  • 16

1 Answers1

2

You are looking for an attribute selector. E.g.,

.bonus-section[value="home]

Demo using a variable below:

const v = "home";

const pickedSection = document.querySelectorAll('.bonus-section[value="' + v + '"]');

console.log('picked Section: ', pickedSection)
<ul>
   <li class="bonus-section" value="home">home</li>
   <li class="bonus-section" value="auto">auto</li>
   <li class="bonus-section" value="life">life</li>
</ul>

Notice that .querySelectoAll() returns a NodeList. If you want just one element, you'll have to use an accessor. E.g,. pickedSection[0].


If, OTOH, you are looking to find all elements with a given content, then you can't do it using a CSS selector alone. You'll have to iterate on the elements returned by a less strict query and filter them by the innerHTML or other:

const v = "home";

const bonusSections = document.querySelectorAll('.bonus-section');
const pickedSection = Array.from(bonusSections).filter((el) => el.innerHTML === v);

console.log('picked Section: ', pickedSection)
<ul>
   <li class="bonus-section" value="home">home</li>
   <li class="bonus-section" value="auto">auto</li>
   <li class="bonus-section" value="life">life</li>
</ul>
acdcjunior
  • 132,397
  • 37
  • 331
  • 304