Can jQuery be used to select a div based on its height? Or is the tutorial wrong?

微笑、不失礼 提交于 2019-12-12 13:24:29

问题


I am trying to select a div based on its height, as shown in this tutorial, jQuery Selection. I cannot get it to work: jsbin example . The line not working is:

   $('div[height=50px]').css('background-color', 'orange');

回答1:


That's an attribute equals selector, so the HTML it would match is:

<div height="50px"></div>

You could change it to:

$('div[style="height:50px"]').css('background-color', 'orange');

According to comments, the above doesn't work in Internet Explorer. Try the following instead:

$('div').filter(function() {
    return $(this).css('height') == '50px';
}).css('background-color', 'orange');

If you want to match other elements with a height of 50px not specified using an attribute, take a look at the .filter() function.




回答2:


If your HTML is...

<div style="height:50px;"></div>

Then your selector should be...

$('div[style*="height:50px"]');

If you are setting height to the value of "50px" and " 50px" (common), you will need to adjust accordingly...

$('div[style*="height:50px"], div[style*="height: 50px"]');

If you change the CSS of this element, the div's style attribute might become: "height:50px;background-color:orange", and it would cease to get picked up by this selector.

Docs: https://api.jquery.com/attribute-contains-selector/



来源:https://stackoverflow.com/questions/11741029/can-jquery-be-used-to-select-a-div-based-on-its-height-or-is-the-tutorial-wrong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!