+ 6
So if you create a element inside function and apply some styles to it ,you need to call that function everytime?
Suppose I created a div element and append it to body but inside function ,but when I try to access the element outside function and apply some styles to it ,it doesn't work
6 Answers
+ 6
Maybe return the newly created element from the function that created it? or if the div was created with an ID, return the ID, and make a reference to it (based on its ID) outside the function.
+ 4
let element;
function create(){
element = document.createElement(...)
}
create()
element.style.....
https://www.sololearn.com/post/45261/?ref=app
+ 3
// Create an add element function using createElement and createTextNode
function createTitle(title) {
var newElement = document.createElement("h1");
var textNode = document.createTextNode(title);
newElement.appendChild(textNode);
newElement.style.color = "red" // apply some css inline styles
return newElement;
}
// Create starting title
document.body.appendChild(createTitle("Hello"))
// Create article title, call the same function again
article.appendChild(createTitle("Hello"))
+ 1
Mirielle ty
+ 1
Ipang ty I didn't thought about it ,I am just not good with functions in js
+ 1
Gordon ty ,i did tried declaring the variable globally and and then assigning newly created element to it but it didn't worked ,and as I didn't called function it was never created!