开发者

How to add class using jQuery when only some element is available on the page?

In page if the table with the class controls is available then only I want to add CSS to a div like overflow-y visible. Using jQuery.

<html>
<body>
<table class="controls" >
</table>
<div style="overflow"></div开发者_运维百科>
</body>
</html>


You can do a simply if check for elements matching the selector (the .length), for example:

if($("table.controls").length) {
  $("div").css({ "overflow-y": "visible" });
}

Though...that "div" selector should be much more specific to what you're after. If you actually want to add the <div> then it would look like this:

$("table.controls").after('<div style="overflow-y: visible;"></div>');


You can use the length property to see if a jQuery object contains any elements:

if ($('table.controls').length > 0) {
  $('div').css('overflow-y','visible');
}


if ( $('table.controls').length ) {
  $('div[style=overflow]').css('overflow-y','visible');
}


$(function(){
  $('.controls').addClassToDiv();
}

$.fn.addClassToDiv = function(){
  return this.each(function(){
    $(this).next('div').addClass('myStyles');
  });
}

You should really keep your styles in your stylesheets rather than adding inline styles, but adding/removing classes is easy. Jut define your new styles in your stylesheet.

The JS adds a jQuery plugin called addClassToDiv that is run on page load, where there’s an element with a class of 'controls' in the page.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜