Home > Software design >  Where did the text of the h1 disappear to?
Where did the text of the h1 disappear to?

Time:01-10

I created and h1 in JS using an API but now it is not appearing on my webpage. If I try to change the style, things around it change but the text still never appears.

Here is my HTML:

<div id="profile-image" ></div>
<div ></div>

Here is my JS:

fetch(GITHUB_URL) 
.then(function(response) {
 return response.json();
 })
.then(function (data) {
 const img = document.createElement('img'); 
 img.src = data.avatar_url;
 img.alt = 'Github prof'
 document.querySelector(".profile-image").appendChild(img); 

 const h1 = document.createElement('h1');
 h1.src = data.name;
 h1.alt = "my name";
 document.querySelector(".profile-name").appendChild(h1);

The image worked and is visible on my webpage. The h1 was supposed to appear underneath that but it is not. When I console.log(data.name) the text that I want appears. There are no errors in my console. Simply the text of the h1 does not appear. Thanks

CodePudding user response:

An HTML heading element does not have src or alt attributes.

Perhaps you mean

const data = {"name": "Fred", "avatar_url": "https://via.placeholder.com/150" }
const img = new Image();
img.src = data.name;
img.alt = 'Github prof';
document.querySelector(".profile-image").appendChild(img);
const h1 = document.createElement('h1');
h1.appendChild(document.createTextNode(data.name));
document.querySelector(".profile-name").appendChild(h1);
<div id="profile-image" ></div>
<div ></div>

CodePudding user response:

h1 tag does not have a src attributes, if you want to show the value in h1 use innerText instead of src

use

const h1 = document.createElement('h1');
 h1.innerText = "sample text";
 h1.alt = "my name";
 document.querySelector(".profile-name").appendChild(h1);
<div ></div>

  • Related