Javascript 1분코딩 (ft.최소 자바스크립트 유목민..그래도 마지막)
-getElementById
-getElementsByTagName
-getAttribute
-setAttribute
혹은
-querySelector(CSS 선택자)
//html code
<h1 id="main-title">DOM (Document Object Model)</h1>
<span>hello 0</span>
<span>hello 1</span>
<span>hello 2</span>
//javascript code
var title=document.getElementById('main-title');
console.log(title);
var titleSpan = title.getElementsByTagName('span');
console.log(titleSpan[0]);
//하면 콘솔 창에 <span>hello</span> 이 출력됨
console.log(titleSpan[2]);
//하면 콘솔창에 <span>hello 2</span>
<h1 id="main-title"> DOM(Document Object Model)</h1>
<small>small</small>
```css
#main-title small {
}
var mainTitle = document.querySelector('#main-title small');
consoe.log(mailTitle); // 하면 <small>small</small> 출력 됨
<li class="jojo"><img src="images/jojo.png"></li>
<li class="jojo"><img src="images/jojo.png"></li>
<li class="jojo"><img src="images/jojo.png"></li>
var jojo = document.querySelector(".jojo");
console.log(jojo); // 출력하면 첫번째 줄만 출력됨, 다 불러오고싶다면
var jojo=document.querySelectorAll(".jojo");
console.log(jojo);// 다 불러와짐, 리스트 세개중 두번째만 출력하고 싶다면?
var jojo=document.querySelectorAll(".jojo");
console.log(jojo[1]); //세개 리스트순서대로 0,1,2 중 두번째값 출력 가능
var jojo=document.query SelectorAll(".jojo");
for(var i=0; i < jojo.length; i++) {
jojo[i].style.border= '1px solid red;
};
<li class="jojo">
<a class="link-google" href="https://google.com">Google</a>
var link=document.querySelector(".jojo a");
console.log(link.getAttribute('href');
//https.//google.com이 출력 됨
link.setAttribute ('href', 'https://studiomeal.com');
console.log(link.getAttribute('href'));
//이렇게 하면 https://studiomeal.com이 출력됨
.special {
background: pink;
}
.link-google {
color: red;
}
var link = document.querySelector('.jojo a');
link.classList.add('speical') ; //classlist라는 객체를 사용, add라는 method 사용 이렇게 하면 pink background와 color red 모두 적용됨.
없앨경우 아래와 같이 remove 사용 가능
link.classList.remove('link-google'); //그럼 default값인 파란색으로 변함
console.log(link.classList.contains('speical');
//true로 출력됨.
var listElem = document.creatElement('li');//list 만들기
console.log(listElem);
///이렇게 하면 <li></li>가 출력됨, 그럼 사이에 text를 넣으려면?
listElem.innerHTML='죠죠';
console.log(listElem)// 하면<li>죠죠</li>로 스캔됨.이제 이걸 집어넣기
<ul class="jojo-mom">
var jojoMom= document.querySelector('.jojo-mom');
var listElem = document.creatElement('li');
listElem.innerHTML='죠죠';
jojoMom.appendChild(listElem);//이렇게 하면 죠죠 리스트가 추가됨