Search code examples
javascripthtmlhtml-lists

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


Solution

  • 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);