Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

210
Views
Programmatically change the src of an img and adding li item in list using javascript

How to change home img src, href and anchor text and in list of HTML and how to Add item in list using javaScript

javascript: (function() {
  document.getElementsByClassName('home')[0].src = 'imagelink.png';
})();
javascript: (function() {
  document.getElementsByClassName('home')[0].href = 'http://www.cnn.com/';
})();
javascript: (function() {
  document.getElementsByClassName('home')[0].innerHTML = 'Main';
})();
<ul class="m_menu_ul box_sizing">
  <li class="home">
    <img src="ld_menu_icon_qa_teal.png">
    <a href="homepage.html">Home</a>
  </li>
 <! -- adding this item as well -->
  <li class="qa">
    <img src="ld_menu_icon_qa_teal.png">
    <a href="quiz.html">Ask the Editor</a>
  </li>
</ul>

I want to like this

enter image description here

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

the document.getElementsByClassName('home') is not a list because you have just a single element with that class name

to make it work you have to select the correct elements:

document.querySelector('.home img').src = 'imagelink.png';
document.querySelector('.home a').href = 'http://www.cnn.com/';
document.querySelector('.home a').innerHTML = 'Main';

To add an item to the list :

const node = document.createElement('li');
node.appendChild(document.createTextNode('core vocabulary'));
 
document.querySelector('.m_menu_ul').appendChild(node);

about 4 years ago · Juan Pablo Isaza Report

0

The issue is, that you change the element with the class home which is a <li>. Use query selector and select the correct child elements (img and a):

javascript: (function() {
  document.querySelector('.home img').src = 'imagelink.png';
})();
javascript: (function() {
  document.querySelector('.home a').href = 'http://www.cnn.com/';
})();
javascript: (function() {
  document.querySelector('.home a').innerHTML = 'Main';
})();
<ul class="m_menu_ul box_sizing">
  <li class="home">
    <img src="ld_menu_icon_qa_teal.png">
    <a href="homepage.html">Home</a>
  </li>
  <li class="qa">
    <img src="ld_menu_icon_qa_teal.png">
    <a href="quiz.html">Ask the Editor</a>
  </li>
</ul>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!