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 badges2 Answers
Reset to default 3There 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")