Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set attribute to a child element

Tags:

javascript

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");
}

Console elements

Any tips welcome.

Thanks

like image 702
Paul Anthony McGowan Avatar asked Oct 18 '25 19:10

Paul Anthony McGowan


1 Answers

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");
}
like image 73
Pranav C Balan Avatar answered Oct 20 '25 08:10

Pranav C Balan