I am trying to use a JavaScript function to change the text in an html span using the class name, but is not working. There is an element with the text "My Tasks", and I am trying to write what I thought was going to be an easy JS function to change the text, but cannot figure it out.
console.log('forgot my JavaScript here');
.helpme {
color: red;
font-size: 2em;
}
<div >I need html here please</div>
CodePudding user response:
to help javascript find the element give it an id:
<span id="foobar" >My Tasks</span>
then do
document.getElementById("foobar").innerHTML = "New Text!";
Note that using a class to find an element is dangerous because generally classes are not unique whereas ids exist to be unique, though HTML will not stop you from duplicating them.
CodePudding user response:
Please keep in mind that using the class you could customize more than one element
Example:
document.querySelector('.your-class').textContent = "Test 2";
<span >Test 1</span>
You can find more information about the querySelector attribute here: Document.querySelector()