Skip to content

Instantly share code, notes, and snippets.

@rtivital
Last active April 11, 2016 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rtivital/dfc3afa4641c919a68448f2cacf37d6e to your computer and use it in GitHub Desktop.
Save rtivital/dfc3afa4641c919a68448f2cacf37d6e to your computer and use it in GitHub Desktop.

Функция $

Может принимать контекст, исходя из которого будут выбираться элементы. Контекст, как и сам элемент может быть в виде:

  1. Строки (.selector, .context)
  2. DOM-элемента (document.querySelector('.selector'), document.querySelector('.context'))
  3. Коллекции DOM-элементов (document.querySelectorAll('.selector'), document.querySelectorAll('.context')) - в этом случае в качестве контекста выбирается первый подходящий элемент
  4. Объект вида $:
var $p = $('p');
$($p); // вернёт исходный $p

Создание элементов с помощью $

В $ можно передать произвольную строку с HTML разметкой. В таком случае функция вернёт коллекцию, созданную с помощью данной строки:

var $p = $('<p class="hello there">Hello</p>'); // {0: p.hello.there, length: 1}
var $links = $('<a href="#0" class="hello there">Hello</a><a href="#0" class="hello there">Hello</a><a href="#0" class="hello there">Hello</a><a href="#0" class="hello there">Hello</a><a href="#0" class="hello there">Hello</a>');
// {0: a.hello.there, 1: a.hello.there, 2: a.hello.there, 3: a.hello.there, 4: a.hello.there, length: 5}

Методы append, prepend, before, after

Вставляют переданную HTML-строку или объект вида $ в разметку:

<!--Исходная разметка-->
<div class="container">
  <button>Hello!</button>
</div>
$('.container').append('<p class="world">There!</p>');
<!--append-->
<div class="container">
  <button>Hello!</button>
  <p class="world">There!</p>
</div>
$('.container').prepend('<p class="world">There!</p>');
<!--prepend-->
<div class="container">
  <p class="world">There!</p>
  <button>Hello!</button>
</div>
$('.container').before('<p class="world">There!</p>');
<!--before-->
<p class="world">There!</p>
<div class="container">
  <button>Hello!</button>
</div>
$('.container').after('<p class="world">There!</p>');
<!--after-->
<div class="container">
  <button>Hello!</button>
</div>
<p class="world">There!</p>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment