Front-End/J-Query

jquery HTML

jQuery - Get

jQuery - Get Content and Attributes

제인쿼리에서 문서 객체를 다루는것

jQuery DOM Manipulation

DOM = Document Object Model        // 문서 객체 모델

Get Content - text(), html(), and val() 

속성 요소를 Get 가져온다.

  • text() - Sets or returns the text content of selected elements
  • html() - Sets or returns the content of selected elements (including HTML markup)
  • val() - Sets or returns the value of form fields
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("#btn1").click(function(){                  // btn2 선택자
        alert("Text: " + $("#test").text());    // btn1 선택자 텍스트 문자만 Get 불러온다
    });
    $("#btn2").click(function(){                  // btn2 선택자
        alert("HTML: " + $("#test").html());  // btn2 html body html태그 모두 Get 불러온다
    });
});
</script>
</head>
<body>

<p id="test">This is some <b>bold</b> text in a paragraph.</p>

<button id="btn1">Show Text</button>
<button id="btn2">Show HTML</button>

</body>
</html>
jQuery val() method - val 변수에 담긴 값 Get
<script>
$(document).ready(function(){
    $("button").click(function(){                // 버튼을 클릭하면
        alert("Value: " + $("#test").val()); // 선택자 "test" val는 입력받은 값 Mickey Mouse 출력
    });                                                      // id="test"에 있는 value 값을 Get = Mickey Mouse
});
</script>
</head>
<body>

<p>Name: <input type="text" id="test" value="Mickey Mouse"></p>

<button>Show Value</button>

</body>
</html>
Get Attributes - attr() - 속성(애트뷰트) 
엘리먼트(요소)
<script>
$(document).ready(function(){
    $("button").click(function(){
        alert($("#w3s").attr("href"));// 하이퍼 레퍼런스(href)속성 값(URL)을 Get 한다
    });
});
</script>
</head>
<body>

<p><a href="https://www.w3schools.com" id="w3s">W3Schools.com</a></p>

<button>Show href Value</button>

</body>
</html>
jQuery - Set Content and Attribute - 

기존에 있었던거에서 새롭게 셋팅한다.

(Set)

Set Content - text(), html(), and val()

We will use the same three methods from the previous page to set content:

  • text() - Sets or returns the text content of selected elements
  • html() - Sets or returns the content of selected elements (including HTML markup)
  • val() - Sets or returns the value of form fields

The following example demonstrates how to set content with the jQuery text(), html(), and val() methods:


<script>
$(document).ready(function(){
    $("#btn1").click(function(){           // text
        $("#test1").text("Hello world!"); // 기존 This is a paragraph 에서 현재 Hello world! 변경
    });
    $("#btn2").click(function(){                          // html
        $("#test2").html("<b>Hello world!</b>"); // 기존 : This is 에서 현재 <b>Hello 변경
    });
    $("#btn3").click(function(){           // val
        $("#test3").val("Dolly Duck");    // 기존 : Mickey 현재 : Dolly Duck 변경
    });
});
</script>
</head>
<body>

<p id="test1">This is a paragraph.</p>
<p id="test2">This is another paragraph.</p>

<p>Input field: <input type="text" id="test3" value="Mickey Mouse"></p>

<button id="btn1">Set Text</button>
<button id="btn2">Set HTML</button>
<button id="btn3">Set Value</button>

</body>
</html>
get 과 set 차이점
get = text(), html(), val() 가져온다
set = text("Hello world"), html("html문서 변수에(소스작성)넣는다"), val(값을 넣는다) 파라미터 값을 직접 넣는다
A Callback Function for text(), html(), and val() - 콜백(function()) 함수
<script>
$(document).ready(function(){
    $("#btn1").click(function(){
        $("#test1").text(function(i, origText){  // 값을 2개 받음 i로 받고 origText 받고 합쳐서 출력
            return "Old text: " + origText + " New text: Hello world! (index: " + i + ")"; 
        });    // Old text 와 New text 합쳐서 출력됨!!!!!! @.@ 어려움
    });
    $("#btn2").click(function(){
        $("#test2").html(function(i, origText){    // 기존 text + newtext 2개 받고 합쳐서 출력
            return "Old html: " + origText + " New html: Hello <b>world!</b> (index: " + i +     ")"; 
        });    // Old text 와 New text 합쳐서 출력됨!!!!!! @.@ 어려움 
    });
});
</script>
</head>
<body>

<p id="test1">This is a <b>bold</b> paragraph.</p>
<p id="test2">This is another <b>bold</b> paragraph.</p>

<button id="btn1">Show Old/New Text</button>
<button id="btn2">Show Old/New HTML</button>

</body>
</html>

Set Attributes - attr() - href 속성 변경하기 콜백

Ex)1

<script>

$(document).ready(function(){

    $("button").click(function(){    // 하이퍼 레퍼런스 href 속성 url 변경

        $("#w3s").attr("href", "https://www.w3schools.com/jquery"); //W3Schools 변경   

    });

});

</script>

</head>

<body>

<p><a href="https://www.w3schools.com" id="w3s">W3Schools.com</a></p>

<button>Change href Value</button>

<p>Mouse over the link (or click on it) to see that the value of the href attribute has changed.</p>

</body>

</html>

Ex)2
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#w3s").attr({
            "href" : "https://www.w3schools.com/jquery",
            "title" : "W3Schools jQuery Tutorial"
        });
    });
});
</script>
</head>
<body>

<p>
<a href="https://www.w3schools.com" title="some title" ="w3s">W3Schools.com</a></p>

<button>Change href and title</button>

<p>
Mouse over the link to see that the href attribute has changed and a title attribute is set.</p>

</body>
</html>

A Callback Function for attr()

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#w3s").attr("href", function(i, origValue){
            return origValue + "/jquery";     // 기존 href url 끝에 /jquery Set 출력
        });
    }); 
});
</script>
</head>
<body>

<p>
<a href="https://www.w3schools.com" id="w3s">W3Schools.com</a>
</p>

<button>Change href Value</button>
<p>
Mouse over the link (or click on it) to see that the value of the href attribute has changed.</p>

</body>
</html>

jQuery - Add Elements - 

엘리먼트(컨텐츠) 추가

  • append() - Inserts content at the end of the selected elements // 컨텐츠를 뒷부분에 추가
  • prepend() - Inserts content at the beginning of the selected elements // 앞부분에 추가
  • after() - Inserts content after the selected elements    // 뒷부분 추가
  • before() - Inserts content before the selected elements    // 앞부분 추가

jQuery append() Method - 뒷부분 추가

<script>
$(document).ready(function(){
    $("#btn1").click(function(){
        $("p").append(" <b>Appended text</b>."); // 기존 텍스트 끝에 추가
    });
    $("#btn2").click(function(){
        $("ol").append("<li>Appended item</li>");  // 기존 텍스트 하단에 컨텐츠 추가
    });
});
</script>
</head>
<body>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<ol>
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>
</ol>

<button id="btn1">Append text</button>
<button id="btn2">Append list items</button>
</body>
</html>

jQuery prepend() Method - 앞부분에 컨텐츠 추가

<script>
$(document).ready(function(){
    $("#btn1").click(function(){
        $("p").prepend("<b>Prepended text</b>. ");  // 기존 텍스트 처음에 추가 
    });
    $("#btn2").click(function(){
        $("ol").prepend("<li>Prepended item</li>");   // 기존 텍스트 윗단에 컨텐츠 추가
    });
});
</script>
</head>
<body>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<ol>
  <li>List item 1</li>
  <li>List item 2</li>
  <li>List item 3</li>
</ol>

<button id="btn1">Prepend text</button>
<button id="btn2">Prepend list item</button>

</body>
</html>

Add Several New Elements With append() and prepend() - JQuery 에서 새로운 엘리먼트 추가

<script>
function appendText() {                              // 매개변수 추가
    var txt1 = "<p>Text.</p>";                   //  Create text with HTML text 1개 추가
    var txt2 = $("<p></p>").text("Text.");  // Create text with jQuery text 1개 추가
    var txt3 = document.createElement("p");
    txt3.innerHTML = "Text.";                   // Create text with DOM  text 1개 추가
    $("body").append(txt1, txt2, txt3);  // Append new elements <body> Append text  
}                                                         // text 3개 추가
</script>
</head>
<body>

<p>This is a paragraph.</p>

<button onclick="appendText()">Append text</button>

</body>
</html>

jQuery after() and before() Methods

<script>
$(document).ready(function(){
    $("#btn1").click(function(){
        $("img").before("<b>Before</b>");  // 선택자 img 앞에 before 출력
    });

    $("#btn2").click(function(){
        $("img").after("<i>After</i>");        // 선택자 img 뒤에 After 출력
    });
});
</script>
</head>
<body>
<img src="/images/w3jquery.gif" alt="jQuery" width="100" height="140"><br><br>
<button id="btn1">Insert before</button>
<button id="btn2">Insert after</button>
</body>
</html>

Add Several New Elements With after() and before() - 각각 엘리먼트 속성에 따라 추가하는 방법

<script>
function afterText() {
    var txt1 = "<b>I </b>";                        // Create element with HTML
    var txt2 = $("<i></i>").text("love ");     // Create with jQuery
    var txt3 = document.createElement("b"); // Create with DOM
    txt3.innerHTML = "jQuery!";
    $("img").after(txt1, txt2, txt3);              // Insert new elements after img
}
</script>
</head>
<body>

<img src="/images/w3jquery.gif" alt="jQuery" width="100" height="140">

<p>Click the button to insert text after the image.</p>
<button onclick="afterText()">Insert after</button>

</body>
</html>
jQuery - Remove Elements - 컨텐츠 제거
  • remove() - Removes the selected element (and its child elements)  // 모두 없어짐
  • empty() - Removes the child elements from the selected element    // 자식만 없어짐

jQuery remove() Method - 모두 없어짐

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").remove();        // 선택한 엘리먼트 중 자식 엘리먼트까지 모두 사라짐
    });
});
</script>
</head>
<body>

<div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">
This is some text in the div.

<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>

</div>

<br>
<button>Remove div element</button>

</body>
</html>

jQuery empty() Method -자식 엘리만 없어짐

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").empty();        // 선택한 자식 엘리먼트만 사라짐
    });
});
</script>
</head>
<body>

<div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">

This is some text in the div.
<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>

</div>
<br>

<button>Empty the div element</button>

</body>
</html>

Filter the Elements to be Removed - 필더

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").remove(".test");        // test 선택자만 찾아서 사라짐
    });
});
</script>
<style>
.test {
    color: red;
    font-size: 20px;
}
</style>
</head>
<body>

<p>This is a paragraph.</p>
<p class="test">This is another paragraph.</p>
<p class="test">This is another paragraph.</p>

<button>Remove all p elements with class="test"</button>

</body>
</html>
// 여기서는 test 선택자와 demo 선택자 사라짐
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").remove(".test, .demo");
    });
});
</script>
<style>
.test {
    color: red;
    font-size: 20px;
}

.demo {
    color: green;
    font-size: 25px;
}
</style>
</head>
<body>

<p>This is a paragraph.</p>
<p class="test">This is p element with class="test".</p>
<p class="test">This is p element with class="test".</p>
<p class="demo">This is p element with class="demo".</p>

<button>Remove all p elements with class="test" and class="demo"</button>

</body>
</html>

jQuery - CSS Classes (CSS 다루기)

jQuery - Get and Set CSS Classes

jQuery Manipulating CSS

  • addClass() - Adds one or more classes to the selected elements        // 지정된 클라스 추가
  • removeClass() - Removes one or more classes from the selected elements    // 지정된 클라스 제거
  • toggleClass() - Toggles between adding/removing classes from the selected elements   
  • // 토글 할때마다 +- 
  • css() - Sets or returns the style attribute    // 속성값 반환

Example Stylesheet

.important {                
    font-weight: bold;
    font-size: xx-large;
}

.blue {
    color: blue;
}
jQuery addClass() Method    - 클라스 추가
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("h1, h2, p").addClass("blue");    // 선택한 엘리먼트가 블루색으로 변경
        $("div").addClass("important");     // div  글자체가 인포턴트로 변경
    });
});
</script>
<style>
.important {
    font-weight: bold;
    font-size: xx-large;
}
.blue {
    color: blue;
}
</style>
</head>
<body>

<h1>Heading 1</h1>
<h2>Heading 2</h2>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<div>This is some important text!</div><br>

<button>Add classes to elements</button>

</body>
</html>

multiple classes within the addClass() method:
클라스 추가 할때 여러가지를 추가할수 있다
<script>
$(document).ready(function(){
    $("button").click(function(){        // 콜백
        $("#div1").addClass("important blue"); // div1 파라미터를 여러개 지정
    });                                                                   // 글자체 변경 색깔변경
});
</script>
<style>
.important {
    font-weight: bold;
    font-size: xx-large;
}

.blue {
    color: blue;
}
</style>
</head>
<body>

<div id="div1">This is some text.</div>
<div id="div2">This is some text.</div>
<br>

<button>Add classes to first div element</button>

</body>
</html>

jQuery removeClass() Method - 클라스 색깔 제거

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("h1, h2, p").removeClass("blue");    // blue 색깔 제거
    });
});
</script>
<style>
.important {
    font-weight: bold;
    font-size: xx-large;
}

.blue {
    color: blue;
}
</style>
</head>
<body>

<h1 class="blue">Heading 1</h1>
<h2 class="blue">Heading 2</h2>

<p class="blue">This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Remove class from elements</button>

</body>
</html>

jQuery toggleClass() Method - On Off

<script>
$(document).ready(function(){
    $("button").click(function(){
        $("h1, h2, p").toggleClass("blue");  // On - 적용 Off - 해제 [클릭할때마다 변경]
    });
});
</script>
<style>
.blue {
    color: blue;
}
</style>
</head>
<body>

<h1>Heading 1</h1>
<h2>Heading 2</h2>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Toggle class</button>

</body>
</html>

CSS 레퍼런스
https://www.w3schools.com/jquery/jquery_ref_html.asp

jQuery - css() Method

하나 이상의 속성값을 반환하거나 변경 

Return a CSS Property - 객체의 속성을 반환(보여)

css("propertyname");
<script>
$(document).ready(function(){
    $("button").click(function(){
        alert("Background color = " + $("p").css("background-color")); // 첫번째 P(엘리)만
    });                                               // Background color (Property 속성값)= rgb(255, 0, 0)
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p style="background-color:#ff0000">This is a paragraph.</p>
<p style="background-color:#00ff00">This is a paragraph.</p>
<p style="background-color:#0000ff">This is a paragraph.</p>

<button>Return background-color of p</button>

</body>
</html>
Set a CSS Property - Set 으로 css 변경
css("propertyname","value");
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").css("background-color", "yellow");    // P엘리먼트 모두 노란색으로 변경
    });
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p style="background-color:#ff0000">This is a paragraph.</p>
<p style="background-color:#00ff00">This is a paragraph.</p>
<p style="background-color:#0000ff">This is a paragraph.</p>

<p>This is a paragraph.</p>

<button>Set background-color of p</button>

</body>
</html>

Set Multiple CSS Properties - 여러게 엘리 속성 변경

css({"propertyname":"value","propertyname":"value",...});
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("p").css({"background-color": "yellow", "font-size": "200%"});
    });
});
</script>
</head>
<body>

<h2>This is a heading</h2>

<p style="background-color:#ff0000">This is a paragraph.</p>
<p style="background-color:#00ff00">This is a paragraph.</p>
<p style="background-color:#0000ff">This is a paragraph.</p>

<p>This is a paragraph.</p>

<button>Set multiple styles for p</button>

</body>
</html>
## CSS 참고 문서
https://www.w3schools.com/jquery/jquery_ref_html.asp
jQuery - Dimensions - 면접 다루기

jQuery Dimension Methods

  • width()
  • height()
  • innerWidth()
  • innerHeight()
  • outerWidth()
  • outerHeight()

jQuery width() and height() Methods - w,h 면적값 반환

<script>

$(document).ready(function(){

    $("button").click(function(){

        var txt = "";

        txt += "Width of div: " + $("#div1").width() + "</br>";

        txt += "Height of div: " + $("#div1").height();

        $("#div1").html(txt);

    });

});

</script>

<style>

#div1 {

    height: 100px;

    width: 300px;

    padding: 10px;

    margin: 3px;

    border: 1px solid blue;

    background-color: lightblue;

}

</style>

</head>

<body>


<div id="div1"></div>

<br>


<button>Display dimensions of div</button>


<p>width() - returns the width of an element.</p>

<p>height() - returns the height of an element.</p>


</body>

</html>

jQuery innerWidth() and innerHeight() Methods

각각 면적 값을 반환
<script>
$(document).ready(function(){
    $("button").click(function(){
        var txt = "";
        txt += "Width of div: " + $("#div1").width() + "</br>";       
        txt += "Height of div: " + $("#div1").height() + "</br>";
        txt += "Inner width of div: " + $("#div1").innerWidth() + "</br>";
        txt += "Inner height of div: " + $("#div1").innerHeight();
        $("#div1").html(txt);
    });
});
</script>
</head>
<style>
#div1 {
    height: 100px;
    width: 300px;
    padding: 10px;
    margin: 3px;
    border: 1px solid blue;
    background-color: lightblue;
}
</style>
<body>

<div id="div1"></div>
<br>

<button>Display dimensions of div</button>

<p>innerWidth() - returns the width of an element (includes padding).</p>
<p>innerHeight() - returns the height of an element (includes padding).</p>

</body>
</html>

jQuery outerWidth() and outerHeight() Methods

각각 면적 값을 반환
Ex1)
<script>
$(document).ready(function(){
    $("button").click(function(){
        var txt = "";
        txt += "Width of div: " + $("#div1").width() + "</br>";
        txt += "Height of div: " + $("#div1").height() + "</br>";
        txt += "Outer width of div: " + $("#div1").outerWidth() + "</br>";
        txt += "Outer height of div: " + $("#div1").outerHeight();
        $("#div1").html(txt);
    });
});
</script>
<style>
#div1 {
    height: 100px;
    width: 300px;
    padding: 10px;
    margin: 3px;
    border: 1px solid blue;
    background-color: lightblue;
}
</style>
</head>
<body>

<div id="div1"></div>
<br>

<button>Display dimensions of div</button>

<p>outerWidth() - returns the width of an element (includes padding and border).</p>
<p>outerHeight() - returns the height of an element (includes padding and border).</p>

</body>
</html>
Ex2)
<script>
$(document).ready(function(){
    $("button").click(function(){
        var txt = "";
        txt += "Width of div: " + $("#div1").width() + "</br>";
        txt += "Height of div: " + $("#div1").height() + "</br>";
        txt += "Outer width of div (margin included): " + $("#div1").outerWidth(true) + "</br>";
        txt += "Outer height of div (margin included): " + $("#div1").outerHeight(true);
        $("#div1").html(txt);
    });
});
</script>
<style>
#div1 {
    height: 100px;
    width: 300px;
    padding: 10px;
    margin: 3px;
    border: 1px solid blue;
    background-color: lightblue;
}
</style>
</head>
<body>

<div id="div1"></div>
<br>

<button>Display dimensions of div</button>

<p>outerWidth(true) - returns the width of an element (includes padding, border, and margin).</p>
<p>outerHeight(true) - returns the height of an element (includes padding, border, and margin).</p>

</body>
</html>

jQuery More width() and height()

Ex1)
<script>
$(document).ready(function(){
    $("button").click(function(){
        var txt = "";
        txt += "Document width/height: " + $(document).width();
        txt += "x" + $(document).height() + "\n";
        txt += "Window width/height: " + $(window).width();
        txt += "x" + $(window).height();
        alert(txt);
    });
});
</script>
</head>
<body>

<button>Display dimensions of document and window</button>

</body>
</html>
Ex2)
<script>
$(document).ready(function(){
    $("button").click(function(){
        $("#div1").width(500).height(500);
    });
});
</script>
<style>
#div1 {
    height: 100px;
    width: 300px;
    padding: 10px;
    margin: 3px;
    border: 1px solid blue;
    background-color: lightblue;
}
</style>
</head>
<body>

<div id="div1"></div>
<br>

<button>Resize div</button>

</body>
</html>


'Front-End > J-Query' 카테고리의 다른 글

jQuery Misc  (0) 2017.07.06
jQuery AJAX  (0) 2017.07.06
jQuery Traversing  (0) 2017.07.06
jQuery Effects  (0) 2017.07.06
jQuery Tutorial  (0) 2017.07.01
,

최근 댓글

최근 트랙백

알림

이 블로그는 구글에서 제공한 크롬에 최적화 되어있고, 네이버에서 제공한 나눔글꼴이 적용되어 있습니다.

태그

카운터

Today :
Yesterday :
Total :