[JavaScript] (해결) 동적으로 font awesome 아이콘 추가하기

나는 쇼핑목록 앱을 만들고있다.

TO DO LIST처럼 쇼핑할 물건들을 적는 리스트이다.


현재 문제점 : appendChild, innerHTML 등을 이용하여 font awesome icon을 추가하려한다.

 

이런식으로. 다만 x 표시(빨간색 화살표로 강조한 부분) 대신에 나는 쓰레기통 아이콘을 사용할 것이다.

fa fa-trash이다.

 

fa-trash: Font Awesome Icons

Get 1535 icons right now with FA Free, plus another 7020 icons with Pro, which also gets you another 53 icon category packs as we finish them! Our all-new SVG with JavaScript gives you all the power of SVG without the usual hassle. Ligatures for easier des

fontawesome.com

 


아이콘 하나인데 이렇게 힘들다니...

 

-appendChild 입력했을 경우(//add a trash bin icon 밑줄을 보면 된다.)

function newElement() {
  //add stuffs
  let li = document.createElement("li");
  li.textContent = input.value;
  input.value = "";
  list.appendChild(li);

  //add a trash bin icon
  li.appendChild('<i class="fa fa-trash" aria-hidden="true"></i>');
}

-경고 문구

main.js:30 Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.

 

 

-innerHTML 입력했을 경우(//add a trash bin icon 밑줄을 보면 된다.)

 

function newElement() {
  //add stuffs
  let li = document.createElement("li");
  li.textContent = input.value;
  input.value = "";
  list.appendChild(li);

  //add a trash bin icon
  li.innerHTML('<i class="fa fa-trash" aria-hidden="true"></i>');
}

 

-경고 문구

main.js:30 Uncaught TypeError: li.innerHTML is not a function

 

 


스택오버플로우를 확인해보자!

 

How to dynamically add a font awesome Icon with javascript?

I have a table and I have it set up to dynamically add rows with a button.I am having some issues figuring out how to dynamically add a font awesome icon to the end. Below is the code to add the ...

stackoverflow.com

 

나와 비슷한 문제를 가진 분이 있었다.

역시 appendChild와 innerHTML로 해결하라는 답변이 있었다..

하지만! 대댓글에 작성자가 다른 방식으로 해결했다는 글이 있다.

 

Thank you for your response but using appendChild did not work. After messing around with it in the console I finally got it to work. e.setAttribute("class","sourceText fa fa-trash-o"); $(e.sourceText).append('<i class="fa fa-trash-o"></i>'); Added the class fa fa-trash-o to the setAttribute and a dollar sign to the next line.

인용구 한번 써봤다.

 

간추려서 작성해봤다.

function newElement() {
  //add stuffs
  let li = document.createElement("li");
  li.textContent = input.value;
  input.value = "";
  list.appendChild(li);

  //add a trash bin icon
  li.setAttribute("class", "fa fa-trash");
}

얏호! 된다. 하지만 단어가 쓰레기통 옆으로 온다..

이제 새롭게 해결한 문제다 화이팅

 


약 다섯시간의 구글링과 고민 끝에

스택오버플로우에 질문을 올렸고, 결국 해결했다.

 

해결방법

2021/01/04 - [IT/JavaScript] - [JavaScript] 동적으로 아이콘 추가하기 해결방법

 

[JavaScript] 동적으로 아이콘 추가하기 해결방법

문제: [JavaScript] (해결) 동적으로 font awesome 아이콘 추가하기 나는 쇼핑목록 앱을 만들고있다. TO DO LIST처럼 쇼핑할 물건들을 적는 리스트이다. 현재 문제점 : appendChild, innerHTML 등을 이용하여 font..

breathtaking-life.tistory.com

 

320x100