So if you create a element inside function and apply some styles to it ,you need to call that function everytime? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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

31st Jul 2020, 10:13 AM
Abhay
Abhay - avatar
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.
31st Jul 2020, 12:58 PM
Ipang
+ 4
let element; function create(){ element = document.createElement(...) } create() element.style..... https://www.sololearn.com/post/45261/?ref=app
31st Jul 2020, 1:13 PM
Gordon
Gordon - avatar
+ 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"))
31st Jul 2020, 1:33 PM
Calviղ
Calviղ - avatar
+ 1
31st Jul 2020, 12:48 PM
Abhay
Abhay - avatar
+ 1
Ipang ty I didn't thought about it ,I am just not good with functions in js
31st Jul 2020, 2:12 PM
Abhay
Abhay - avatar
+ 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!
31st Jul 2020, 2:13 PM
Abhay
Abhay - avatar