When I add <br>
through DOM, it isn't working properly...
The <br>
isn't doing its job. Everything else is working perfectly fine. I think it is some problem with .append()
method...
Here is the live demo (Note: The live demo is now fixed. But the below code is of the non-fixed) Here is the code:
JS:
const urls = [
{
src:
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRtFPba2-cBeIyhZ3Sxlkd2fGZegsdcqEEoww&usqp=CAU",
name: "John Doe",
email: "[email protected]"
}
];
urls.forEach((person) => {
const profile = document.createElement("div");
const img = document.createElement("img");
img.src = person.src;
const hr = document.createElement("hr");
const name = document.createTextNode("Name: " person.name);
const br = document.createElement("br");
const email = document.createTextNode("Email: " person.email);
profile.append(img, hr, name, br, email);
document.body.append(profile, br);
});
CSS:
div {
border: 5px solid #ca6702;
width: 300px;
height: 500px;
margin: 0 auto;
background-color: #2a9d8f;
}
img {
width: 300px;
border: 4px solid #264653;
box-sizing: border-box;
border-radius: 50%;
}
hr {
height: 3px;
background-color: #e9d8a6;
}
CodePudding user response:
Using document.createElement()
creates only 1 element and you can append it to the dom only once. Creating a second one or cloning your br
should fix your issue.
const urls = [
{
src:
"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRtFPba2-cBeIyhZ3Sxlkd2fGZegsdcqEEoww&usqp=CAU",
name: "John Doe",
email: "[email protected]"
}
];
urls.forEach((person) => {
const profile = document.createElement("div");
const img = document.createElement("img");
img.src = person.src;
const hr = document.createElement("hr");
const name = document.createTextNode("Name: " person.name);
const br = document.createElement("br");
const br2 = document.createElement("br");
const email = document.createTextNode("Email: " person.email);
profile.append(img, hr, name, br, email);
document.body.append(profile, br2);
});
CodePudding user response:
Every time you append a <br>
element, you need to create it one more time to append it again. In your case it can look like this:
const br1 = document.createElement("br");
const email = document.createTextNode("Email: " person.email);
profile.append(img, hr, name, br1, email);
const br2 = document.createElement("br");
document.body.append(profile, br2);