Not selector in javascript

Using CSS Selectors In Javascript

In CSS, selectors are patterns used to select the element(s) you want to style, but as you can tell from the title above, selectors are also useful in javascript and below are some examples on how to use them.

Basics

Using a selector in javascript

const div = document.querySelector("div") // => First occurence of a div element in the document const p = div.querySelector("p") // => First occurence of a p element in the div 
document.querySelectorAll("div") // NodeList of all div elements 

By IDs

To get an element by its ID, use a # before the element ID

document.querySelector("#id") // => document.getElementById('id') 

By classes

To get elements by class, use a . before the class name

document.querySelectorAll(".myElementClass") 

By tag name

To get elements by tag name, just input the tag name

document.querySelectorAll("body") // => document.getElementsByTagName('body') 

Replicating .getElementById and getElementsByTagName

document.querySelector("#myDivId") // => document.getElementById('myDivId') 
document.querySelectorAll("a") // => document.getElementsByTagName('a') 

All elements

document.querySelectorAll("*") // => NodeList[. ] 

Using multiple selectors

To use multiple selectors, we seperate each of them with a , .

   Hello i am a paragraph  href="https://awesomeplace.com">Hey I am a link  href="https://anotherplace.com">I am another link   
document.querySelectorAll("p, a") // => NodeList[p,a,a] 

More with elements

In the above examples, we made basic queries, but other things can be done like getting elements by order or parent.

Getting element children

There are two variants of this, one gets an element’s child no matter how deep it is down the tree, and the other gets an element’s direct child.

   Hello i am a paragraph  href="https://awesomeplace.com">Hey I am a link Hello i am a paragraph and here's  href="https://anotherplace.com">a link     

With the above HTML as an example, we will look at these two variants.

document.querySelectorAll("div a") // => NodeList[a,a] 

Getting elements by order

There are two ways to do this also. Consider the following HTML.

    href="https://awesomeplace.com">Hey I am a link I should intervene but i wont Hello i am another paragraph  Hello i am a paragraph   
document.querySelector("div + p") // => 

Hello i am a paragraph

With ~ , it does not matter the element immediately behind matches.

document.querySelector("a ~ p") // => 

Hello i am another paragraph

and we can see that the pre element did not affect the result because it does not matter if the pre was there in the first place. But the following selector will fail because it checks the element immediately above it.

document.querySelector("a + p") // => null 

Getting elements by attribute

An attribute selector starts with [ and ends with ] and is used as such

   style="color:blue;">Hello i am styled Hello i have no style   

document.querySelector("p[style]") // => 

Hello i am styled

Check attribute value

To check an attribute value we use the = symbol.

   href="https://awesomeplace.com">Hey I am a link  href="https://anotherplace.com">I am another link   

Источник

Читайте также:  Java class file metadata

Not selector in javascript

Description: Remove elements from the set of matched elements.

version added: 1.0 .not( selector )

A string containing a selector expression, a DOM element, or an array of elements to match against the set.

version added: 1.4 .not( function )

A function used as a test for each element in the set. It accepts two arguments, index , which is the element’s index in the jQuery collection, and element , which is the DOM element. Within the function, this refers to the current DOM element.

version added: 1.4 .not( selection )

Given a jQuery object that represents a set of DOM elements, the .not() method constructs a new jQuery object from a subset of the matching elements. The supplied selector is tested against each element; the elements that don’t match the selector will be included in the result.

Consider a page with a simple list on it:

ul>
li>list item 1 li>
li>list item 2 li>
li>list item 3 li>
li>list item 4 li>
li>list item 5 li>
ul>

We can apply this method to the set of list items:

$( "li" ).not( ":nth-child(2n)" ).css( "background-color", "red" );

The result of this call is a red background for items 1, 3 and 5, as they do not match the selector.

Removing Specific Elements

The second version of the .not() method allows us to remove elements from the matched set, assuming we have found those elements previously by some other means. For example, suppose our list had an id applied to one of its items:

ul>
li>list item 1 li>
li>list item 2 li>
li id="notli">list item 3 li>
li>list item 4 li>
li>list item 5 li>
ul>

We can fetch the third list item using the native JavaScript getElementById() function, then remove it from a jQuery object:

$( "li" ).not( document.getElementById( "notli" ) )
.css( "background-color", "red" );

This statement changes the color of items 1, 2, 4, and 5. We could have accomplished the same thing with a simpler jQuery expression, but this technique can be useful when, for example, other libraries provide references to plain DOM nodes.

As of jQuery 1.4, the .not() method can take a function as its argument in the same way that .filter() does. Elements for which the function returns true are excluded from the filtered set; all other elements are included.

Note: When a CSS selector string is passed to .not() , text and comment nodes will always be removed from the resulting jQuery object during the filtering process. When a specific node or array of nodes are provided, text or comment nodes will only be removed from the jQuery object if they match one of the nodes in the filtering array.

Читайте также:  Div header image html

Examples:

Adds a border to divs that are not green or blue.

Источник

:not() Selector

Description: Selects all elements that do not match the given selector.

version added: 1.0 jQuery( «:not(selector)» )

All selectors are accepted inside :not() , for example: :not(div a) and :not(div,a) .

Additional Notes

The .not() method will end up providing you with more readable selections than pushing complex selectors or variables into a :not() selector filter. In most cases, it is a better choice.

Example:

Finds all inputs that are not checked and highlights the next sibling span. Notice there is no change when clicking the checkboxes since no click events have been linked.

html>
html lang="en">
head>
meta charset="utf-8">
title>not demo title>
script src="https://code.jquery.com/jquery-3.7.0.js"> script>
head>
body>
div>
input type="checkbox" name="a">
span>Mary span>
div>
div>
input type="checkbox" name="b">
span>lcm span>
div>
div>
input type="checkbox" name="c" checked="checked">
span>Peter span>
div>
script>
$( "input:not(:checked) + span" ).css( "background-color", "yellow" );
$( "input").attr( "disabled", "disabled" );
script>
body>
html>

Demo:

  • 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 :not() Selector

    The :not() selector selects all elements except the specified element.

    This is mostly used together with another selector to select everything except the specified element in a group (like in the example above).

    Syntax

    Parameter Description
    selector Required. Specifies the element to not select.
    This parameter accepts any kind of selector

    Unlock Full Access 50% off

    COLOR PICKER

    colorpicker

    Join our Bootcamp!

    Report Error

    If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

    Thank You For Helping Us!

    Your message has been sent to W3Schools.

    Top Tutorials
    Top References
    Top Examples
    Get Certified

    W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

    Источник

    jQuery селектор отрицания :not

    jQuery селектор отрицания :not позволяет выбрать элементы отличные от указанных. Селектор отрицания используется вместе с другим селектором, чтобы выбрать все элементы, кроме указанных в селекторе.

    jQuery синтаксис:

    Обратите внимание на отличие от синтаксиса CSS и jQuery при использовании некоторых селекторов:

    CSS: a:not(:last-child)  блок объявлений; > jQuery: $( "a:not(a:last-child)" ) // необходимо продубировать селектор типа a 

    Добавлен в версии jQuery

    Селектор в CSS

    css3

    CSS селектор :not (псевдокласс отрицания).

    Пример использования

       Использование jQuery селектора отрицания :not p:not(:first-child)  /* выбирает все элементы 

    , за исключением тех, которые являются первым дочерним элементом своего родителя */ font-weight: bold; /* определяет жирное начертание символов */ > $( document ).ready(function() $( "p:not(p:first-child)" ).css("color", "red"); // выбирает и стилизует все элементы

    , за исключением тех, которые являются первым дочерним элементом своего родителя $( "p:not(.test)" ).css("text-decoration", "underline"); // выбирает и стилизует все элементы

    , за исключением тех, которые имеют класс test >); Первый абзац

    class = "test">Второй абзац Третий абзац

    css3

    • С использованием CSS селектора отрицания селектор :not выбрали все элементы , за исключением тех, которые являются первыми дочерними элементами своего родителя. В нашем случае это первый абзац и стилизовали установив жирное начертание символов второму и третьему абзацу.
    • С использованием jQuery селектора отрицания :not выбрали и стилизовали (цвет текста красный) все элементы , за исключением тех, которые являются первыми дочерним элементами своего родителя (в нашем случае первый абзац). Обратите внимание на отличие в синтаксисе между CSS и jQuery. jQuery необходимо явно указать какой первый дочерний элемент имеется ввиду, в нашем случае мы дублируем селектор типа p.
    • С использованием jQuery селектора отрицания :not выбрали и стилизовали (декорирование текста — нижнее подчеркивание) все элементы , за исключением тех, глобальный атрибут class которых, имеет значение «test» .

    Пример использования jQuery селектора отрицания :not.

    jQuery селекторы

    © 2016-2023 Денис Большаков, замечания и предложения по работе сайта Вы можете направить по адресу basicweb.ru@gmail.com

    Кажется, вы используете блокировщик рекламы 🙁

    Этот ресурс не является коммерческим проектом и развивается на энтузиазме автора сайта, который посвящает все свое свободное время этому проекту.

    Добавьте, пожалуйста, basicweb.ru в исключения блокировщика рекламы, этим вы поможете развитию проекта.

    Источник

Оцените статью