My goal is to have it move back and forth with the button presses as if its an actual cursor
<div>
hello<span id="hi"></span>
</div>
<button onclick="move('left')">left</button>
<button onclick="move('right')">right</button>
i can't figure out how to locate the span in the text and then move it to the side with the button presses so it goes from hello| to hell|o with one press to the left
function move(direction){
switch (direction) {
case "left":
break;
case "right":
break;
}
}
all the css is fine
span {
content: '';
width: 3px;
height: 17px;
background: black;
opacity: 0;
display: inline-block;
animation: blink 0.5s linear infinite alternate;
}
@keyframes blink {
50% {
opacity: 0;
}
100% {
opacity: 1;
}
}
The way you need to think about this is that your document is a tree (as in the data structure) because that is how the browser sees it. That means means the part that you are working with is three sections:
div
.....[text]
..... span
.....[text]
div
All three are children of your parent div, so they will be in its childNodes collection. Two are text nodes, the other is a span element.
The text node type has a textContent property, which you can use to get or set the text within the node. Something like this:
const myDiv = document.getElementsByTagName('div')[0]; // assuming you only have one div, more practical to give your div an id and use document.getElementById("my-id");
myDiv.childNodes[0].textContent = "hello";
This looks a little homework-adjacent and certainly seems a good opportunity for learning, so instead of writing the code, I'll take the long cut. The process I would go through in your function is:
div - perhaps having an id on it would make that easier.textContent of its first child.textContent of its last child.Note that doing it this way, we aren't doing anything with the span we are moving the text around it instead.
For extra flourish you could create an object that maintains references to the text nodes in question so you don't have to retrieve them each time a button is clicked.