+ 1
JavaScript & CSS: Styling an Array
I want to add color to an array which picks one word randomly and inserts the word into a sentence which is called by the element id. Iāve got the array set so every time a button is clicked the word changes to a different word in the array, but I canāt get the one word to be a different color than the rest of the sentence. My question is, how do I simultaneously set the id for the element and the class for the object within the element?
2 Answers
+ 3
Without your code we cannot help you efficiently ^^
However, your question is unclear... What are you meaning by "simultaneously" ? When you set the id of an element, and then the class of it ( the class of an element aply style to the element content, you cannot set "class for the object within the element" but only set class for an element, even if it's a child of another one -- meaning a element inside another one ), both are applyed ( displayed ) "simultanesously", even if both assignement are not done "simultaneously"... And why want you "set" the element id ? Are you creating the element dynamically ?
Anyway, there's many way to reach a goal, but if you have html:
<p id="sentence">my <span id="word">word</span> inside a sentence</p>
...and you want to change the "word", you could simply access it by:
my_word = document.getElementById('word'); // get the reference of the targeted element
my_word.innerHTML = 'new'; // change (replace) the content of the targeted element
my_word.className = 'my_class'; // change (replace) the 'class' attribute of the targeted element
But you could also get the targeted reference by other way, including :
my_word = document.querySelector('#sentence > span'); // use css selectors syntax to got the reference of an element (ie: if you don't have a specific id on it).
If you are creating dynamically the element (quite the only good reason to "set" it an id), you could do something like:
my_new_element = document.createElement('span');
my_new_element.id = 'my_new_element_id';
my_new_element.className = 'a_class_name_to_apply_some_style_on_the_newly_created_element';
document.getElementById('sentence').appendChild(my_new_element); // will add the new element as last child of the element with 'sentence' as id
But you should provide yor code to get further and better suited help according to your specific context, without disturbing you with generic case and wich doesn't fit and have place here :P
+ 1
Thank you so much, this helps abundantly. I figured out how to apply the style to the script within the HTML by changing the id word, turns out that was my missing link, just as you explained. Due to my limited (currently expanding) knowledge, I didn't ask the question correctly lol thank you again!!