0

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)
}
11
  • 2
    Do you mean that element has an inline style (i.e. <div style="font-weight: bold">) ? Commented Nov 18, 2019 at 12:47
  • Yes. So that Javascript looks for all elements in a class that have that style Commented Nov 18, 2019 at 12:53
  • 1
    Then try this document.querySelectorAll('.menuulli[style="font-weight: bold;"]') Commented Nov 18, 2019 at 12:59
  • Now when i have this: var array = document.querySelectorAll('.menuulli[style="font-weight: bold;"]'); console.log(array) It just gives me "NodeList []" in the console. And there is an element that has this css property. Commented Nov 18, 2019 at 13:05
  • 1
    Look at this example: jsfiddle.net/Konrud/g7vzc9s5 Works perfect for me. Commented Nov 18, 2019 at 13:13

4 Answers 4

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

You are the only one realizing that bold can actually be internally converted to number, kudos!
1

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

Comments

0

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]);
}

Comments

0

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");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.