-2

How do you access a certain div that has a certain CSS property?

For example:

<div class="container">
  <div id=1 class="child"></div>
  <div id=2 class="child"></div>
  <div id=3 class="child"></div>
  . .
  <div id=50 class="child" style= "background:yellow;"></div>
  . . .
  <div id=100 class="child"></div>
</div>

So, how can I access the div with the background: yellow and retrieve its id?

The div with the yellow background changes to different div so will right this in jQuery?

Jake quin
  • 738
  • 1
  • 9
  • 25

2 Answers2

1

You should be using style="background:yellow", not "styles:". Anyway, this is how you can work with it:

const div = document.querySelector('div[style="background:yellow;"]').id;
Darren
  • 710
  • 1
  • 6
  • 11
  • 1
    This will work in the above case, but not if there are other css properties set in style, for example, it won't work if I have `
    `
    – Aleks G Oct 01 '18 at 16:25
  • im getting a null from div, i only want thevalue of id though, is this the way to do it? – Jake quin Oct 01 '18 at 16:59
  • Ah, sorry, I forgot to add on the `.id`, but if you're getting null, that means the selector is incorrect. Replace the `"style="background:yellow;"` bit with exactly what you have in your HTML, and it should be fine. Right now you have `styles: "background:yellow;"`, which is wrong. So whatever you correct that to, make sure it's reflected in the code above. – Darren Oct 01 '18 at 17:03
0

First of all you've a typo in :

<div id=50 class="child" styles: "background:yellow;"></div>
______________________________^^^ //Must be singulare 'style' plus an equal like `style=`

You could select by the attribute style like 'div[style="background:yellow;"]' :

 console.log( $('div[style="background:yellow;"]').prop('id') );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div id=1 class="child"></div>
  <div id=2 class="child"></div>
  <div id=3 class="child"></div>
  . .
  <div id=50 class="child" style="background:yellow;"></div>
  . . .
  <div id=100 class="child"></div>
</div>

NOTE 1: If there's more rules inside the style attribute value we could use contains selector *= like:

$('div[style*="background:yellow;"]').prop('id');
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101