简体   繁体   中英

Change the Text in HTML with span class using Javascript

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 class="helpme">I need html here please</div>

部分 HTML 正文的屏幕截图

to help javascript find the element give it an id:

<span id="foobar" class="toolbartitle">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.

Please keep in mind that using the class you could customize more than one element

Example:

 document.querySelector('.your-class').textContent = "Test 2";
 <span class="your-class">Test 1</span>

You can find more information about the querySelector attribute here: Document.querySelector()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM