Jquery find all css

Category: CSS

These methods get and set CSS-related properties of elements.

.addClass()

Adds the specified class(es) to each element in the set of matched elements.

Get the value of a computed style property for the first element in the set of matched elements or set one or more CSS properties for every matched element.

.hasClass()

Determine whether any of the matched elements are assigned the given class.

.height()

Get the current computed height for the first element in the set of matched elements or set the height of every matched element.

.innerHeight()

Get the current computed inner height (including padding but not border) for the first element in the set of matched elements or set the inner height of every matched element.

.innerWidth()

Get the current computed inner width (including padding but not border) for the first element in the set of matched elements or set the inner width of every matched element.

jQuery.cssHooks

Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize CSS property naming, or create custom properties.

jQuery.cssNumber

An object containing all CSS properties that may be used without a unit. The .css() method uses this object to see if it may append px to unitless values.

jQuery.escapeSelector()

Escapes any character that has a special meaning in a CSS selector.

.offset()

Get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document.

.outerHeight()

Get the current computed outer height (including padding, border, and optionally margin) for the first element in the set of matched elements or set the outer height of every matched element.

.outerWidth()

Get the current computed outer width (including padding, border, and optionally margin) for the first element in the set of matched elements or set the outer width of every matched element.

.position()

Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

.removeClass()

Remove a single class, multiple classes, or all classes from each element in the set of matched elements.

.scrollLeft()

Get the current horizontal position of the scroll bar for the first element in the set of matched elements or set the horizontal position of the scroll bar for every matched element.

.scrollTop()

Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element.

.toggleClass()

Add or remove one or more classes from each element in the set of matched elements, depending on either the class’s presence or the value of the state argument.

.width()

Get the current computed width for the first element in the set of matched elements or set the width of every matched element.

  • Ajax
    • Global Ajax Event Handlers
    • Helper Functions
    • Low-Level Interface
    • Shorthand Methods
    • Deprecated 1.3
    • Deprecated 1.7
    • Deprecated 1.8
    • Deprecated 1.9
    • Deprecated 1.10
    • Deprecated 3.0
    • Deprecated 3.2
    • Deprecated 3.3
    • Deprecated 3.4
    • Deprecated 3.5
    • Basics
    • Custom
    • Fading
    • Sliding
    • Browser Events
    • Document Loading
    • Event Handler Attachment
    • Event Object
    • Form Events
    • Keyboard Events
    • Mouse Events
    • Class Attribute
    • Copying
    • DOM Insertion, Around
    • DOM Insertion, Inside
    • DOM Insertion, Outside
    • DOM Removal
    • DOM Replacement
    • General Attributes
    • Style Properties
    • Collection Manipulation
    • Data Storage
    • DOM Element Methods
    • Setup Methods
    • Properties of jQuery Object Instances
    • Properties of the Global jQuery Object
    • Attribute
    • Basic
    • Basic Filter
    • Child Filter
    • Content Filter
    • Form
    • Hierarchy
    • jQuery Extensions
    • Visibility Filter
    • Filtering
    • Miscellaneous Traversing
    • Tree Traversal
    • Version 1.0
    • Version 1.0.4
    • Version 1.1
    • Version 1.1.2
    • Version 1.1.3
    • Version 1.1.4
    • Version 1.2
    • Version 1.2.3
    • Version 1.2.6
    • Version 1.3
    • Version 1.4
    • Version 1.4.1
    • Version 1.4.2
    • Version 1.4.3
    • Version 1.4.4
    • Version 1.5
    • Version 1.5.1
    • Version 1.6
    • Version 1.7
    • Version 1.8
    • Version 1.9
    • Version 1.11 & 2.1
    • Version 1.12 & 2.2
    • Version 3.0
    • Version 3.1
    • Version 3.2
    • Version 3.3
    • Version 3.4
    • Version 3.5
    • Version 3.6
    • Version 3.7

    Books

    Copyright 2023 OpenJS Foundation and jQuery contributors. All rights reserved. See jQuery License for more information. The OpenJS Foundation has registered trademarks and uses trademarks. For a list of trademarks of the OpenJS Foundation, please see our Trademark Policy and Trademark List. Trademarks and logos not indicated on the list of OpenJS Foundation trademarks are trademarks™ or registered® trademarks of their respective holders. Use of them does not imply any affiliation with or endorsement by them. OpenJS Foundation Terms of Use, Privacy, and Cookie Policies also apply. Web hosting by Digital Ocean | CDN by StackPath

    Источник

    jQuery find all css classes and its css attributes inside a certain div

    The following tutorial shows you how to do «jQuery find all css classes and its css attributes inside a certain div».

    The result is illustrated in the iframe.

    You can check the full source code and open it in another tab using the links.

    Javascript Source Code

    The Javascript source code to do «jQuery find all css classes and its css attributes inside a certain div» is

    var selector;// w ww . d e m o 2 s . c o m window.result=[]; var sheets = document.styleSheets; for (var i in sheets) < var rules = sheets[i].rules || sheets[i].cssRules; for (var r in rules) < selector=rules[r].selectorText; rule=rules[r].cssText; $('.demo, .demo *').each(function () < //console.log($(this),selector); if ($(this).is(selector)) < result.push(rule); >>); > > console.log(result); $('#output').html(result.join("
    "
    ));
    html> head> meta name="viewport" content="width=device-width, initial-scale=1"> script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.js" > style id="compiled-css" type="text/css"> .demo!-- w w w . d e m o 2 s . c o m --> height:100px; width:100px; background:#FF0; > .new_classheight:40px; width:40px; background:#999;> #paracolor:#E1E1E1;>  body> div >"demo"> div >"new_class"> p id="para">This is Demo Paragraph a style="background:#ccc">HyperLink   div id='output' style='padding-top:20px;'>  script type='text/javascript'> var selector; window.result=[]; var sheets = document.styleSheets; for (var i in sheets) < var rules = sheets[i].rules || sheets[i].cssRules; for (var r in rules) < selector=rules[r].selectorText; rule=rules[r].cssText; $('.demo, .demo *').each(function () < //console.log($(this),selector); if ($(this).is(selector)) < result.push(rule); >>); > > console.log(result); $('#output').html(result.join("
    "
    ));

    • jQuery find a class within a div id (Demo 2)
    • jQuery find a class within a div id (Demo 3)
    • jQuery find a sibling cell using class names
    • jQuery find all css classes and its css attributes inside a certain div
    • jQuery find all elements of a given class not in a particular id container
    • jQuery find all elements of a given class not in a particular id container (Demo 2)
    • jQuery find all the id’s associated with a particular class

    demo2s.com | Email: | Demo Source and Support. All rights reserved.

    Источник

    Может ли jQuery получить все стили CSS, связанные с элементом?

    Есть ли способ в jQuery, чтобы получить все CSS из существующего элемента и применить его к другому без перечисления их всех? Я знаю, что это сработает, если они были атрибутом стиля с attr() , но все мои стили находятся во внешней таблице стилей.

    5 ответов

    function css(a) < var sheets = document.styleSheets, o = <>; for (var i in sheets) < var rules = sheets[i].rules || sheets[i].cssRules; for (var r in rules) < if (a.is(rules[r].selectorText)) < o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style'))); >> > return o; > function css2json(css) < var s = <>; if (!css) return s; if (css instanceof CSSStyleDeclaration) < for (var i in css) < if ((css[i]).toLowerCase) < s[(css[i]).toLowerCase()] = (css[css[i]]); >> > else if (typeof css == "string") < css = css.split("; "); for (var i in css) < var l = css[i].split(": "); s[l[0].toLowerCase()] = (l[1]); >> return s; > 

    Передайте объект jQuery в css() , и он вернет объект, который затем можно подключить к jQuery $().css() , ex:

    var style = css($("#elementToGetAllCSS")); $("#elementToPutStyleInto").css(style); 

    это выглядит потрясающе, но когда я пытаюсь это сделать, оно пропускает некоторые свойства, такие как font-family.

    @ Damon: Это верное предположение, учитывая, что первая строка ответа говорит . вот решение, которое извлекает как встроенное, так и внешнее оформление .

    @ Damon это не пропускает определенные свойства, встроенные или нет. Я только что проверил это сам. Не могли бы вы предоставить jsfiddle или gist, показывающие, что он не работает? В остальном все работало просто отлично.

    Одна из проблем с отличным решением — некоторые браузеры применяют одну и ту же политику происхождения и устанавливают для cssRules значение null .

    +1, но кажется уязвимым для стилей с более высоким приоритетом, если они находятся в неправильном порядке в таблице стилей. Решение этого может быть довольно сложным и, вероятно, дорогим.

    Только что попробовал использовать код, он, кажется, сорвался, выдав мне эту ошибку в chrome: Uncaught Error: синтаксическая ошибка, нераспознанное выражение: button.ui-button :: — moz-focus-inner

    «button.ui» нигде не встречается в этом коде, поэтому я не уверен, как он может иметь синтаксическую ошибку на этом? Вы уверены, что это не плагин для браузера? Я не могу получить ошибку, чтобы это произошло. Есть JSFiddle?

    Предоставление патча / исправления или jsFiddle, которое точно указывает, где именно происходит ваша ошибка (если таковая имеется), будет высоко цениться — для поддержки вашего заявления и предоставления информации для других. Спасибо!

    Примечание: getMatchedCSSRules в настоящее время реализовано только в браузерах Webkit ( таблица совместимости ), поэтому использование этого в Firefox или IE вызовет проблемы. Вам понадобится полифилл для обработки этого кода.

    Примечание: Модераторы изменили мой оригинальный код, я не даю никаких гарантий, что все будет работать.

    Обратите внимание, что это не возвращает стили браузера по умолчанию, а только стили, которые были применены таблицами стилей или встроенными.

    Не работает для меня, я тестировал в Chrome консоли. это не работает. Когда я ставлю «var style = css (jQuery (‘# main input’));» после выполнения функции css () я получил следующую ошибку «Uncaught Syntax error, нераспознанное выражение: hover»

    CORS начинает меня раздражать со всей своей отсталостью: вы получите Error: The operation is insecure. если CSS с удаленного сайта .

    вот скрипка моей версии, которая очень похожа, но не подавляет псевдо-селекторы. также есть демо: jsfiddle.net/a2f0phg5/1

    Я обнаружил, что это решение не подходит, если вы используете @import, каким-то образом, кроме, конечно, не использования @import?

    Присоединяясь @Mike Хочу напомнить, что приведенные выше решения не копируют состояния наведения, активных и т. Д. Выбранных элементов. : — /

    @bencergazda Я не пробовал, но если вам нужно: hover, вы можете вызвать наведение мыши. Не уверен, что вы могли бы стать активными. Может быть, вызывает муссоун? Попробуйте.

    Этот код теперь вызывает Error: The operation is insecure в Firefox Error: The operation is insecure (chrome все еще работает). Это связано с .cssRules в var rules = sheets[i].rules || sheets[i].cssRules; , Вам нужно будет попробовать / поймать эту строку, чтобы защитить Firefox.

    Два года спустя, но у меня есть решение, которое вы ищете. Не намереваясь взять кредит у оригинального автора, здесь плагин, который я нашел, работает исключительно хорошо для того, что вам нужно, но получает все возможные стили во всех браузерах, даже IE.

    Предупреждение: Этот код генерирует много результатов и должен использоваться экономно. Он не только копирует все стандартные свойства CSS, но и все свойства CSS для этого браузера.

    /* * getStyleObject Plugin for jQuery JavaScript Library * From: http://upshots.org/?p=112 */ (function($)< $.fn.getStyleObject = function()< var dom = this.get(0); var style; var returns = <>; if(window.getComputedStyle)< var camelize = function(a,b)< return b.toUpperCase(); >; style = window.getComputedStyle(dom, null); for(var i = 0, l = style.length; i < l; i++)< var prop = style[i]; var camel = prop.replace(/\-([a-z])/g, camelize); var val = style.getPropertyValue(prop); returns[camel] = val; >; return returns; >; if(style = dom.currentStyle)< for(var prop in style)< returns[prop] = style[prop]; >; return returns; >; return this.css(); > >)(jQuery); 

    Основное использование довольно простое, но он также написал для этого функцию:

    $.fn.copyCSS = function(source)

    Источник

    Читайте также:  Php зайти по root
Оцените статью