StudioTime
StudioTime

Reputation: 23959

Get element attributes within inline styles

I have the following html block:

<div class="container">
 <div class="class" style="left:100px; top:0px">
 <div class="class" style="left:200px; top:0px">
 <div class="class" style="left:200px; top:100px">
</div>

I need to get the position of each from the inline css, how can I do that?

I know I can't use .attr() or js getAttribute as this would return the whole style block.

I ideally I'd like something like:

$(".container> .class").each(function(){
  var context = $(this);
  var thisLeft = context.left; // which I know is incorrect
}

Is this possible? JQuery or vanilla fine

Upvotes: 1

Views: 131

Answers (2)

Alex Char
Alex Char

Reputation: 33218

Anoter solution is to use jquery map and get the value of all like:

var pos = $(".container > .class").map(function() {
  return {
    left: $(this).css("left"),
    top: $(this).css("top"),
    right: $(this).css("top"),
    bottom: $(this).css("bottom"),
  }
}).get();

console.log(pos);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="class" style="left:100px; top:0px"></div>
  <div class="class" style="left:200px; top:0px"></div>
  <div class="class" style="left:200px; top:100px"></div>
</div>

Upvotes: 2

Amit Joki
Amit Joki

Reputation: 59232

In jQuery, you would do $(this).css('left')

$(".container> .class").each(function(){
    var thisLeft = $(this).css('left');
});

As @Fred said, usage of this.style.left doesn't care for the styles applied to the elements using style blocks or external css files, so just use $.fn.css method.

Upvotes: 3

Related Questions