DEV Community

Dahye Ji
Dahye Ji

Posted on

jQuery, Ajax, Axios


jQuery is JavaScript library.
jQuery CDN:
jQuery CDN
You can check from the latest version. If you click one of the links, you can get the CDN link for jQuery. I used minified for jQuery 3.x
Copy and paste the link inside the head tag in html file(and it should be above your css link). Because it's read from top to bottom - if your css link is above the jQuery link, your css might not work like you expected.

 <!-- jQuery CDN: -->
 <script src=""
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
Enter fullscreen mode Exit fullscreen mode

jQuery documentation

Read Documentation:
You can find anything you'd like to do with jQuery if you use search box. It shows you how to use jQuery with examples.


You can select elements with id, class and tag name like you do in css but you should use dollar sign and parentheses $()
For example, if you'd like to select an element with id name "item", $("#item"). If the element has class "box", then $(".box") and for h2 tag, $("h2").
(If it was javascript you have to write like document.querySelector("#item") or document.getElementByID("item") which is very long.)

  • .parent(): gets the ancestors of each element in the current set of matched elements, optionally filtered by a selector. Usage eg) $('.items').parent().css('backgroundColor', 'blue');
  • .children(): gets the children of each element in the set of matched elements, optionally filtered by a selector. Usage eg) $('.ul2').children('li:gt(5)').css('color', 'blue').css('backgroundColor', 'red')
  • .siblings() gets the siblings of each element in the set of matched elements, optionally filtered by a selector.

Using jQuery

  • .html(): is used to set an element's content. It's to write html.
  • .css(): as a setter, jQuery modifies the element's style property. For example, $("#mydiv").css("color", "green") is equivalent to document.getElementById("mydiv").style.color = "green".
  • .attr(): a convenient way to set the value of attributes
  • val(): allows you to pass an array of element values

jQuery filter

  • :eq: equal( = ) $("li").eq(2).css("color", "blue" ); means change color to blue for li element on the index 2.
  • :lt: little ( < ), stands for the less-than sign $("li:lt(2)") means li elements that have smaller index than 2.
  • :gt: greater ( > ), stands for the greater-than sign $("li:gt(4)").css( "backgroundColor", "yellow"); means change background color to yellow for li elements that have greater index than 4.
  • :not(selector): $("input:not(:checked)+span").css("backgroundColor", "yellow"); means change background color to yellow for the span that is next to input not checked.
  • :even: even elements in that set.
  • :odd: odd elements in that set.
  • :first: the first element in that set.
  • :last: the last element in that set
// example
$( "li" ).filter(":nth-child(2n)").css("backgroundColor", "red" );
Enter fullscreen mode Exit fullscreen mode

filter by attribute

  • attributeContains - input[name*="name"]: It will select an element if the selector's string appears anywhere within the element's attribute value. Usage eg) $("input[name*='man']").val("has man in it!");
  • attributeEquals - input[name="value"]: Selects elements that have the specified attribute with a value exactly equal to a certain value. Usage eg) $("input[value='Hot Fuzz']").next().text("Hot Fuzz");

child filter

  • :first-child: first-child selector can match more than one. one for each parent. This is equivalent to nth-child(1).
  • :last-child: selects all elements that are the last child of their parent. last-child selector can match more than one. one for each parent.
  • :nth-child(2): implementation of :nth- selectors is strictly derived from the CSS specification, the value of n is "1-indexed", meaning that the counting starts at 1
  • :nth-child(even): even number indexed elements
  • :nth-child(odd): odd number indexed elements

content filter

  • :contains(text): select all elements that contain the specified text. Usage eg) $("div:contains('shop')").css("text-decoration", "underline");
  • :empty: removes all child nodes of the set of matched elements from the DOM. Usage eg) $(".hello").empty();
  • :has(selector): selects elements which contain at least one element that matches the specified selector

class attribute

  • .addClass() : adds the specified class(es) to each element in the set of matched elements.
  • .removeClass() : remove a single class, multiple classes, or all classes from each element in the set of matched elements.
  • .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.
  • .hasClass() : determine whether any of the matched elements are assigned the given class.

editing with jQuery

$("p").append("Some appended text.");
$("p").prepend("Some prepended text.");
$('ul').after('<h2>The end!</h2>');

// You can use - and camelCase but it's good to use one fixed.
Enter fullscreen mode Exit fullscreen mode

effects with jQuery

Enter fullscreen mode Exit fullscreen mode

jQuery practice

<!DOCTYPE html>
<html lang="ko">

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- -->
    <!-- 3점대 minified 사용함 -->
    <script src=""
        integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
        // 문사가 다 준비되면 실행.
        $(function () { // 이것을 주석처리하면 실행이 안됩니다.
            //html이 다 로드되지 않은 상태이기 떄문에 그렇습니다.
        .box {
            width: 200px;
            height: 200px;
            background-color: palevioletred;

        .box2 {
            width: 100px;
            height: 100px;
            opacity: 0.3;
            background-color: red;

    <h1 id="one">jQuery 실습</h1>
    <button class="btn1">클릭해!!</button>
    <p class="실습">jQuery 실습을 하고 있습니다.</p>
    <textarea name="메모장" id="메모장" cols="30" rows="10"></textarea>
    <button class="btn2">메모장 내용 경고창으로 출력</button>
    <p id="p3">hello world</p>
        1. li items 부모를 찾아 background-color를 파란색으로 버꿔주세요.
        2. items 2번째 색을 빨간색으로 바꿔주세요.
        3. ul2의 자식인 li요소를 선택하여 1번부터 3번까지 color를 녹색으로 바꿔주세요.
        4. ul2의 자식인 li요소를 선택하여 7번부터 10번까지 color를 파란색, background-color를 빨간색으로 바꿔주세요.
    <div class="wrapper">
        <h1 class="title">TITLE</h1>
            <li class="items">item1</li>
            <li class="items">item2</li>
            <li class="items">item3</li>
    <!-- ul>li{hello}*10 -->
    <ul class="ul2">
    <div id="div1">Hello world!</div>
    <div class="one blue">hello world</div>
    <div class="two blue">hello world</div>
    <p class="blue">hello world</p>
    <div class="three">hello</div>
    <div class="three blue">hello</div>
    <div class="box">hello world</div>
    <div class="box2">hello world</div>
    <button class="btn3">눌러봐요!</button>
        // document.getElementById('one').innerHTML = "!!!";
        // class는 . 아이디는 #
        $('#one').text('hello jquery');
        // $('p').hide(); // display: none 됨
        $('.btn1').click(function () {
        // $('.실습').text('<strong>실습</strong>중이에요');
        $('.실습').css('color', 'red');
        $('.실습').css('backgroundColor', 'blue');

        // camelCase is used in jQuery
        $('img').attr('src', '../html/img/a.jpg',);
        $('img').attr('data-name', '프로필').attr('data-hello', 'world');
        $('img').css({ 'width': '400px', 'height': '280px' });

        $('.btn2').click(function () {
            let 메모장값 = $('#메모장').val();
            $('#메모장').val('값을 입력하세요.');
        $('#p3').css('color', 'red').css('backgroundColor', 'blue');

        $('.items').parent().css('backgroundColor', 'blue');
        $('.items').eq(1).css('color', 'red');
        // $('.ul2 > li:lt(3)').css('color', 'green');
        // $('.ul2').children('li:lt(3)').css('color', 'green');
        $('.ul2:nth-child(n+3)').css('color', 'green')
        // $('.ul2 > li:gt(5)').css('color', 'blue').css('backgroundColor', 'red');
        $('.ul2').children('li:gt(5)').css('color', 'blue').css('backgroundColor', 'red')

        // append는 마지막에 추가됨 
        // 홑따옴포, 쌍타옴표는 JSON에서만 주의하면 되고 아무거나 사용해도 되긴함.(보통 회사 컨벤션에 맞게 사용)
        // ul 복수개를 잡음!
        $('ul').append("<li>hello world end</li>");
        // append는 앞에 추가됨  (ul의 자식에 추가)
        $('ul').prepend("<li>hello world start</li>");
        // after는 ul 다음에 추가
        // this removes the element
        // $('#div1').remove()
        $('.one, .two, p').removeClass('blue');
        // toggle은 없으면 생기고 있으면 없어지게
        // 모달창에서 사용한 사례가 있음
        $('.box').click(function () {
        // div 클릭했을 때 안 보이게 하기
        // dom이 준비되면 실행해라!
        $(function () {
            $('.box').click(function () {
        //JQuery - animate
        //버튼 클릭했을 때 변화주기
        $('.btn3').click(function () {
                width: '300px',
                height: '300px',
                opacity: 1,
            }, 'slow');

        $(".box2").hover(function () {
            $(this).css("background-color", "yellow");
        }, function () {
            $(this).css("background-color", "blue");

        $('.box2').mouseenter(function () {
            alert("You entered!");
        $('.box2').mouseleave(function () {
            alert("Bye! You now leaved");


Enter fullscreen mode Exit fullscreen mode


<div id="box"></div>
Enter fullscreen mode Exit fullscreen mode
// hover - change color(when hover, background color to yellow, when it's not hover than blue)
  $(this).css("background-color", "yellow");
}, function(){
  $(this).css("background-color", "blue");
Enter fullscreen mode Exit fullscreen mode

mouse event

    alert("You entered p1!");
    alert("Bye! You now leaved p1!");
Enter fullscreen mode Exit fullscreen mode

jQuery plugins

Ajax (Asynchronous Javascript and XML)

Find more about Ajax

  $('#btn_data').click(function () {

        $('#btn_data2').click(function () {
            $("#data2").load('https://testtest/main/index.html h1');

        $('#btn_data3').click(function () {
            $("#data3").load('https://testtest/main/index.html h1', function (responseText, statusText, xhr) {

        $('#btn_data4').click(function () {
            //$.ajax({route, sync status, things to do when it succed})
            //$.ajax({url:'route', async: false, success:function(result){}})
                url: 'https://testtest/main/index.html',
                async: true,
                success: function (result) {


Enter fullscreen mode Exit fullscreen mode


Axios is a promise-based HTTP Client for node.js and the browser. It is isomorphic (= it can run in the browser and node.js with the same codebase). On the server-side it uses the native node.js http module, while on the client (browser) it uses XMLHttpRequests.

const url = '';
        axios.get(url).then((response) => { console.log(response) });
Enter fullscreen mode Exit fullscreen mode
Learn about Axios

(I learnt about Ajax and Axios briefly, will write detailed post when I learn node.js later)

Discussion (2)

bogdanbatsenko profile image

jQuery is a controversial topic. I am self-taught developer. I struggled hard learning vanilla JS, neglecting jQuery. Strange as it may seem, I know Vanilla JS better than jQuery. Now I got offer from a company and they asked if I knew jQuery. Your post is exactly on time.

daaahailey profile image
Dahye Ji Author

I heard that jQuery is used less than before but there are many places still using it. I personally prefer Vanilla JS than jQuery since it was first time for me to use it and it was more confusing to me but I think it's better if you know both anyways :)