Varun Verma
Varun Verma

Reputation: 501

jquery manipulation on element attributes

so the problem is like : I am generating a html block with json and final html look like this :

<section class="imagesec" img-width="400">
    <button>click me</button>
    <img src="xyx.jpg"> <!-- image actual width = 400px -->
    <hr>
</section>
<section class="imagesec" img-width="300">
    <button>click me</button>
    <img src="abc.jpg"> <!-- image actual width = 300px -->
    <hr>
</section>

and so it goes on ....
...
...

So i am setting "img-width" attribute in "section" tag for specifying the width of image in it .

What i Want to do ? I just want to hide all section with class = imagesec , which can be done like this

$("section.imagesec").hide()

And then display all sections which contains images of width higher than 350 px . so one way to do this is like getting all section elements then loop over each of them and get value of attribute "img-width" and compare it with 350 , if its more than that display current html object otherwise hide it .

But i want is something like this is possible in jquery ???

$("section.imagesec").hide()
$("section.imagesec").having(attr(img-width) > 350).show()

IN SHORT : I just want to hide all sections which contain images with width less than 350px .

EDIT : img-width="400" not img-width="400px"

Upvotes: 1

Views: 86

Answers (3)

Dejan.S
Dejan.S

Reputation: 19118

To fix your html5 syntax and do it more proper. You should use the data- on html elements to "store" values. This below is the new html and the jQuery from other answers (I take no credit for that).

DEMO

<section class="imagesec" data-img-width="400">
    <button>click me</button>
    <img src="xyx.jpg"> <!-- image actual width = 400px -->
    <hr>
</section>


$('section.imagesec[data-img-width]').filter(function(){
  return (parseInt($(this).attr('data-img-width'),10) < 350);
}).show();

Upvotes: 1

charlietfl
charlietfl

Reputation: 171679

You can use filter()

$("section.imagesec").hide().filter(function(){
   return parseInt($(this).attr('img-width'),10) > 350 ;
}).show();

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try to use .filter() with its call back to accomplish your task,

$('section.imagesec[img-width]').filter(function(){
  return (parseInt($(this).attr('img-width'),10) < 350);
}).hide();

DEMO

Upvotes: 5

Related Questions