I need to add an <a>
link to the end of a paragraph – using a function.
I tried to add a element.style.display = "inline-block"
to it – but that doesn’t seem to work.
I guess I must put the <a>
inside the <p>
itself, but I haven’t seen anything about that anywhere, I know there is only:
a getElementById(idName).appendChild(letA)
– which adds the element after the specified html element.
and getElementById(idName).insertBefore(letA)
– which adds the element before the html element or replaces it with one of its children.
Is there any way in JavaScript to make something like that:
<p>
blah blah blah blah blah blah blah
blah blah blah blah blah blah blah
blah blah blah blah blah blah blah
<a>
</p>
Here is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>
fsdfdfkdsfsmdfskfsgsv snbk skv sdnsskfjdsfskdfsfs
<br>
<br>
fsdfdfkdsfsmdfskfsgsv snbk skv sdnsskfjdsfskdfsfs
<br>
<br>
fsdfdfkdsfsmdfskfsgsv snbk skv sdnsskfjdsfskdfsfs
<br>
<br>
fsdfdfkdsfsmdfskfsgsv snbk skv sdnsskfjdsfskdfsfs
<br>
<br>
fsdfdfkdsfsmdfskfsgsv snbk skv sdnsskfjdsfskdfsfs
<br>
<br>
fsdfdfkdsfsmdfskfsgsv snbk skv sdnsskfjdsfskdfsfs
<br>
<br>
fsdfdfkdsfsmdfskfsgsv snbk skv sdnsskfjdsfskdfsfs
<br>
<br>
fsdfdfkdsfsmdfskfsgsv snbk skv sdnsskfjdsfskdfsfs
<br>
<br>
fsdfdfkdsfsmdfskfsgsv snbk skv sdnsskfjdsfskdfsfs
</p>
<script>
let cube = document.createElement('a');
cube.style.color = "white";
cube.style.backgroundColor = "green";
cube.innerHTML = "hellow whats uppp!!!!"
document.body.appendChild(cube);
</script>
</body>
</html>
2
Answers
You’ll need to use
appendChild
on the DOM element you want it to be a child of, in your case the<p>
At first you must create element.
Then you need to edit it with href or text.
And then use
appendChild()
.If you want to add it at the beginning use
prepend()
;