最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Set attribute to a child element - Stack Overflow

programmeradmin1浏览0评论

I am trying to set an id attribute "gradient" to child element of the main one, which is grabbed by its id of "bg-gradient" , with below code, seems simple but its not working. Code is below, and the id "bg-gradient" is the only one in the document. It should set an id of "gradient" to the next div class "bg-gradient" when click the edit button but doesn't.

editSwatch() {
 let elem = document.getElementById('#bg-gradient');
 elem.childElement.setAttribute("id","gradient");
}

Any tips wele.

Thanks

I am trying to set an id attribute "gradient" to child element of the main one, which is grabbed by its id of "bg-gradient" , with below code, seems simple but its not working. Code is below, and the id "bg-gradient" is the only one in the document. It should set an id of "gradient" to the next div class "bg-gradient" when click the edit button but doesn't.

editSwatch() {
 let elem = document.getElementById('#bg-gradient');
 elem.childElement.setAttribute("id","gradient");
}

Any tips wele.

Thanks

Share Improve this question asked Apr 10, 2020 at 8:28 Paul Anthony McGowanPaul Anthony McGowan 3071 gold badge3 silver badges16 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

There is no childElement property for the DOM element instead use firstElementChild property to get the first child. In addition to that remove # from the argument since getElementById requires an id value and not a CSS selector.

editSwatch() {
 let elem = document.getElementById('bg-gradient');
 elem.firstElementChild.setAttribute("id", "gradient");
}


Or alternately you can use querySelector method to get the element.

editSwatch() {
 document.querySelector('#bg-gradient > .bg-gradient').setAttribute("id", "gradient");
}

change

let elem = document.getElementById('#bg-gradient'); to

let elem = document.getElementById('bg-gradient');

and change

elem.childElement.setAttribute("id","gradient"); to

elem.firstElementChild.setAttribute("id","gradient");

dont put #. It is used by jquery like $("#bg-gradient")

发布评论

评论列表(0)

  1. 暂无评论