<!DOCTYPE html>
<html>
<head>
<title>JavaScript Elements</title>
</head>
<body>
<div>
<ul id='hello-list'>
<li>list1</li>
<li>list2</li>
<li>list3</li>
</ul>
</div>
<script type="text/javascript">
var list4 = document.createElement("li");
var node = document.createTextNode("Hello World");
list4.appendChild(node);
var element = document.getElementById("hello-list");
element.appendChild(list4);hello-list
</script>
</body>
</html>
새 HTML 엘리먼트를 추가하려면 createElement()나 createTextNode() 메서드를 이용해 HTML 엘리먼트를 생성한 다음 그것을 기존 엘리먼트에 덧붙이면 된다.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="parent-id">
<p>hello word1</p>
<p class="test">hello word2</p>
<p >hello word3</p>
<p>hello word4</p>
</div>
<script>
var parentDOM = document.getElementById("parent-id");
var test=parentDOM.getElementsByClassName("test");//test is not target element
console.log(test);//HTMLCollection[1]
var testTarget=parentDOM.getElementsByClassName("test")[0];//hear , this element is target
console.log(testTarget);//<p class="test">hello word2</p>
</script>
</body>
</html>
jQuery에서 특정 돔요소 삭제
<html>
<head>
<style>
p {
background: yellow;
margin: 6px 0;
}
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Hello</p> how are
<p>you?</p>
<button>Call remove() on paragraphs</button>
<script>
$("button").click(function() {
$("p").remove();
});
</script>
</body>
</html>
$("element").remove()를 사용해 삭제할 수 있다. hello를 포함한 모든 문단 제거 시
$("p").remove(":contains('Hello')");
를 사용한다.
<!DOCTYPE html>
<html>
<body>
<h1 onclick="changeText(this)">Click on this text!</h1>
<script>
function changeText(id) {
id.innerHTML = "Ooops!";
}
</script>
</body>
</html>
elements가 0 보다 큰 동안 parentNode.removeChild()를 이용해 삭제한다.
<!DOCTYPE html>
<html>
<body>
<button id="myBtn" onclick="displayDate()">Try it</button>
<div class="test">TEST</div>
<p id="demo"></p>
<script>
// if you use jQuery, $('.test').remove();
function removeElementsByClass(className){
var elements = document.getElementsByClassName(className);
while(elements.length > 0){
elements[0].parentNode.removeChild(elements[0]);
}
}
function displayDate() {
document.getElementById("demo").innerHTML = Date();
removeElementsByClass("test");
}
</script>
</body>
</html>
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate");
해당 인자의 인덱스를 반환한다.
var pos = str.indexOf("locate",15);
searches a string for a specified value and returns the position of the match
var str = "Please locate where 'locate' occurs!";
var pos = str.search("locate"); // 7
slice() 메서드는 특정 문자열의 특정 부분을 잘라낼 수 있다.
var str = "Apple, Banana, Kiwi";
var res = str.slice(7,13); // Banana
파라메터가 음수면 문자열 반대방향으로 부터 계산되어 잘라낸다.
var str = "Apple, Banana, Kiwi";
var res = str.slice(-12, -6); // Banana
var str = "Apple, Banana, Kiwi";
var res = str.slice(7); // Banana, Kiwi
var str = "Apple, Banana, Kiwi";
var res = str.substring(7, 13); // Banana
var str = "Apple, Banana, Kiwi";
var res = str.substr(7, 6); // Banana
replace() 메서드는 문자열을 찾아서 대체할 수 있다.
str = "Please visit Microsoft!";
var n = str.replace("Microsoft", "W3Schools");
모든 문자열의 대체가 필요하다면 정규식 표현법에 의해 /g 옵션을 사용한다.
str = "Please visit Microsoft and Microsoft!";
var n = str.replace(/Microsoft/g, "W3Schools");
concat() joins two or more strings:
var text1 = "Hello";
var text2 = "World";
var text3 = text1.concat(" ", text2); // Hello World!
charAt() method returns the character at a specified index (position)
var str = "HELLO WORLD";
str.charAt(0); // returns H
charCodeAt() method returns the unicode of the character at a specified index in a string
var str = "HELLO WORLD";
str.charCodeAt(0); // returns 72
A string can be converted to an array with the split()
var str = "a,b,c,d,e,f";
var arr = str.split(",");
document.getElementById("demo").innerHTML = arr[0]; / a
var txt = "Hello"; // String
txt.split(""); // Split in characters
var cars = ["Saab", "Volvo", "BMW"];
var cars = new Array("Saab", "Volvo", "BMW");
var person = ["John", "Doe", 46];
var person = {firstName:"John", lastName:"Doe", age:46}; document.getElementById("demo").innerHTML = person.lastName;
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element (Lemon) to fruits
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
var x = person.length; // person.length will return 3
var y = person[0]; // person[0] will return "John"
var person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
var x = person.length; // person.length will return 0
var y = person[0]; // person[0] will return undefined
toString()
var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.toString(); // Banana,Orange,Apple,Mango
join()
var fruits = ["Banana", "Orange", "Apple", "Mango"]; document.getElementById("demo").innerHTML = fruits.join(" * "); // Banana * Orange * Apple * Mango
pop() method removes the last element from an array
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.pop(); // Removes the last element ("Mango") from fruits
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var x = fruits.pop(); // the value of x is "Mango"
push() method adds a new element to an array (at the end)
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.push("Kiwi"); // Adds a new element ("Kiwi") to fruits
var fruits = ["Banana", "Orange", "Apple", "Mango"]; var x = fruits.push("Kiwi"); // the value of x is 5
shift() method removes the first array element and "shifts" all other elements to a lower index
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.shift(); // Removes the first element "Banana" from fruits
unshift() method adds a new element to an array (at the beginning)
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.unshift("Lemon"); // Adds a new element "Lemon" to fruits
append a new element to an array
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits[fruits.length] = "Kiwi"; // Appends "Kiwi" to fruit
elements can be deleted by using the JavaScript operator delete
var fruits = ["Banana", "Orange", "Apple", "Mango"]; delete fruits[0]; // Changes the first element in fruits to undefined
sort() method sorts an array alphabetically
var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort(); // Sorts the elements of fruits
reverse() method reverses the elements in an array
var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a - b}); // 1,5,10,25,40,100
Use the same trick to sort an array descending
var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return b - a}); //100,40,25,10,5,1
var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return 0.5 - Math.random()});
var points = [40, 100, 1, 5, 25, 10]; points.sort(function(a, b){return a - b}); // now points[0] contains the lowest value // and points[points.length-1] contains the highest value
var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}];
cars.sort(function(a, b){return a.year - b.year});
<!DOCTYPE html>
<html>
<body>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="message"></p>
<script>
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
}
</script>
</body>
</html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p id="demo"></p>
<script>
var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>
</body>
</html>
Storing Data
//Storing data: myObj = { "name":"John", "age":31, "city":"New York" }; myJSON = JSON.stringify(myObj); localStorage.setItem("testJSON", myJSON); //Retrieving data: text = localStorage.getItem("testJSON"); obj = JSON.parse(text); document.getElementById("demo").innerHTML = obj.name;
How to loop through all properties in a JSON object
var myObj = { "name":"John", "age":30, "car":null }; for (x in myObj) { document.getElementById("demo").innerHTML += x + "<br>"; } Result: name age car
document.getElementById("demo").innerHTML += myObj[x] + "<br>";
John
30
null
myObj = {
"name":"John",
"age":30,
"cars": {
"car1":"Ford",
"car2":"BMW",
"car3":"Fiat"
}
}
You can access nested JSON objects by using the dot notation or bracket notation
x = myObj.cars.car2; //or: x = myObj.cars["car2"];
to modify any value
myObj.cars.car2 = "Mercedes";
to delete properties from a JSON object
delete myObj.cars.car2;
{
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}
x = myObj.cars[0]; // using index x -> Ford
You can access array values by using a for-in loop
for (i in myObj.cars) { x += myObj.cars[i]; }
Result:
Ford
BMW
Fiat
Or you can use a for loop:
for (i = 0; i < myObj.cars.length; i++) { x += myObj.cars[i]; }
myObj = {
"name":"John",
"age":30,
"cars": [
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"BMW", "models":[ "320", "X3", "X5" ] },
{ "name":"Fiat", "models":[ "500", "Panda" ] }
]
}
To access arrays inside arrays, use a for-in loop for each array
<html>
<body>
<p>Looping through arrays inside arrays.</p>
<p id="demo"></p>
<script>
var myObj, i, j, x = "";
myObj = {
"name":"John",
"age":30,
"cars": [
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"BMW", "models":[ "320", "X3", "X5" ] },
{ "name":"Fiat", "models":[ "500", "Panda" ] }
]
}
for (i in myObj.cars) {
x += "<h2>" + myObj.cars[i].name + "</h2>";
for (j in myObj.cars[i].models) {
x += myObj.cars[i].models[j] + "<br>";
}
}
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
You can request JSON from the server by using an AJAX request
As long as the response from the server is written in JSON format, you can parse the string into a JavaScript object.
Use the XMLHttpRequest to get data from the server:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
"어떤 것을 완전히 알려거든 그것을 다른 이에게 가르쳐라."
- Tryon Edwards -