[jQuery] 동적 생성한 태그에 attribute 추가하기

서울시 미세먼지 API를 활용한 fetch 실습 강의 수강 중 특정 조건에서 빨간 글씨로 출력하기 위해 아래와같은 코드를 사용하였다.

let tmp_html = ``;
if(gu_mise > 40) {
    tmp_html = `<li class="bad">${gu_name} : ${gu_mise}</li>`;
}
else {
    tmp_html = `<li>${gu_name} : ${gu_mise}</li>`;
}

$('#names-q1').append(tmp_html);

 

동일한 부분은 한번에 처리하고 조건에따라 달라져야하는 부분만 따로 처리할 방법을 고민해보고싶어 이것저것 찾아보고 시도해보았다!

 

처음 시도한 방법

문자열 보간

let li_class = gu_mise > 40 ? "class=bad" : "";
let test_html = `<li ${li_class}>${gu_name} : ${gu_mise}</li>`;

$('#names-q1').append(test_html);

 

append 하기위해 만들었던 객체가 문자열이라는 점에서 착안하여 문자열 보간을 사용하였다.

하지만 이 실습에서는 조건에 해당하는 태그에만 클래스를 붙여주면 되는데, 해당하지 않는 태그에도 굳이 빈 문자열을 추가하게 되는 것이 마음에 들지 않아 다른 방법을 찾아보았다.

 

 

jQuery 메서드

내가 원하는대로 조건에 해당할 때만 클래스를 추가하고싶다면, append할 객체 자체가 attribute를 갖고있어야한다는 생각이 들었다. 문자열은 해당되지 않기에 jQuery에서 html 요소를 추가할 수 있는 방법들을 찾아보았고 강의에서 다룬 문자열을 활용하는 방법 외에도 jQuery 객체를 생성하여 추가할 수 있다는 것을 알게되었다!

 

아래는 jQuery 객체를 생성한 뒤 메서드를 이용해 attribute를 추가한 방법들이다.

 

.attr()

메서드를 사용하는 요소의 속성값을 받아오거나 설정할 수 있다.

// 속성값 받아오기
object.attr(attribute 이름);

// 속성값 설정하기
object.attr(attribute 이름, 설정할 값);

 

관련 문서

 

.attr() | jQuery API Documentation

Description: Get the value of an attribute for the first element in the set of matched elements. The .attr() method gets the attribute value for only the first element in the matched set. To get the value for each element individually, use a looping constr

api.jquery.com

 

 

let test_html = $('<li>').text(`${gu_name} : ${gu_mise}`);

if(gu_mise > 40) {
	test_html.attr("class", "bad");
}

$('#names-q1').append(test_html);

 

조건에 해당할 때만 해당 메서드를 활용하여 class를 설정해주었다.

 

.addClass()

객체를 생성하는 방법이 헷갈려 찾아보다가 발견한 메서드

속성값을 인자로 넘겨주면 class를 추가한다.

object.addClass(클래스 이름);

 

관련 문서

 

.addClass() | jQuery API Documentation

Description: Adds the specified class(es) to each element in the set of matched elements. It's important to note that this method does not replace a class. It simply adds the class, appending it to any which may already be assigned to the elements. Before

api.jquery.com

 

let test_html2 = $(`<li>${gu_name} : ${gu_mise}</li>`);
if(gu_mise > 40) {
    test_html2.addClass("bad");
}

$('#names-q1').append(test_html2);

 

마찬가지로 조건에 해당할 때만 메서드를 사용하도록 했다.

.text() 를 활용해 생성한 요소의 텍스트를 변경하지 않아도 리터럴 템플릿을 활용하는 것도 가능했다.

 

 

결과

bad 클래스에 적용하고 싶었던 color: red가 모두 알맞게 적용된 모습이다!

중간에 엉뚱하게 헤매서 시간이 좀 걸렸지만 해결하고나니 뿌듯했다 ㅎㅎㅎ