THE INN-VISIBLE THE INN-VISIBLE - 6 months ago 10
HTML Question

How to group elements based on same specific css attribute using java script or jQuery?

I am working on a page that returns in which i am having many tags that have same css attribute values, i want to see how many types of different values of specific css attribute i am having.

<p style="position:absolute;left:387.5px;top:204px">1</p>
<p style="position:absolute;left:47.5px;top:204px">2</p>


&

<p style="position:absolute;left:387.5px;top:500px">1</p>
<p style="position:absolute;left:47.5px;top:500px">1</p>


i want that i should get two types of values 204 and 500 as result of same css property 'top' !

Answer

You can use $.map(), $.unique(), .filter(), .css()

$(function() {

  $.map(
    // filter unique `css` `top` values, remove duplicates
    $.unique(
      // return `css` `top` values
      $.map($("p"), function(el) {
        return $(el).css("top")
      })
    ), function(val, key) {
      // create new container for grouping elements 
      // having same `css` `top` value
      $("<div>", {
          // filter `p` elements having same `css` `top` value
          html: $("p").filter(function() {
            return $(this).css("top") === val
          })
        })
        // append container `div` to `body`
        .appendTo("body")
    })

})
}
) div {
  border: 1px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<p style="position:absolute;left:387.5px;top:204px">1</p>
<p style="position:absolute;left:387.5px;top:500px">1</p>
<p style="position:absolute;left:47.5px;top:204px">2</p>
<p style="position:absolute;left:47.5px;top:500px">1</p>

Comments