Home > database >  Programmatically change the src of an img and adding li item in list using javascript
Programmatically change the src of an img and adding li item in list using javascript

Time:06-10

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 >
  <li >
    <img src="ld_menu_icon_qa_teal.png">
    <a href="homepage.html">Home</a>
  </li>
 <! -- adding this item as well -->
  <li >
    <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

CodePudding user response:

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 >
  <li >
    <img src="ld_menu_icon_qa_teal.png">
    <a href="homepage.html">Home</a>
  </li>
  <li >
    <img src="ld_menu_icon_qa_teal.png">
    <a href="quiz.html">Ask the Editor</a>
  </li>
</ul>

CodePudding user response:

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';

  • Related