Daniel Jenßen
Daniel Jenßen

Reputation: 53

Get all elements from class with specific css style

I want to get the first element that has style.fontWeight = 'bold';

Heres what i tried

function navigate(input) {
  var array = document.querySelectorAll('.menuulli').style.fontWeight == 'bold';
  console.log(array)
}

Upvotes: 0

Views: 203

Answers (4)

Konrud
Konrud

Reputation: 1114

Use querySelectorAll with the attribute selector:

const array = document.querySelectorAll('.menuulli[style="font-weight: bold;"]'); 

console.log(array);

If you have a more than one style declaration on your HTML tag. For example: <div class"menuulli" style="color: red; font-weight: bold;">

Then use this selector:

/// note the asterisk
const arr = document.querySelectorAll('.menuulli[style*="font-weight: bold;"]');

Here is a JSFiddle example: jsfiddle.net/Konrud/g7vzc9s5

Upvotes: 1

Mamun
Mamun

Reputation: 68933

Since bolder, bold, normal all maps to their corresponding numerical values for the weight of the fonts you can try the following way:

function navigate(){
  var els = document.querySelectorAll('.menuulli');
  els = [...els].filter(el => {
    return getComputedStyle(el).fontWeight == "700"
  })[0];
  return els;
}
console.log(navigate());
.menuulli{
  font-weight: bold;
}
<ul>
  <li class="menuulli first">1</li>
  <li class="menuulli">2</li>
</ul>

Upvotes: 2

Amit
Amit

Reputation: 4290

querySelectorAll returns a NodeList so you cant check for styles on that but you have to check on items.

function navigate(input) {

const elems = document.querySelectorAll('.menuulli');
const elemsArray = Array.from(elems);
array = elemsArray.map((ele)=>
ele.style.fontWeight === "bold");
}

Upvotes: 0

deepak thomas
deepak thomas

Reputation: 1180

You can find the first element by

function navigate(input) {
  var list=[];	
  var array = document.querySelectorAll('a.js-gps-track');
  array = array.forEach(function(ele){if(ele.style.fontWeight === "bold"){list.push(ele);}});
  console.log(list[0]);
}

Upvotes: 0

Related Questions