The screen displays the following
target1 target2 target3 target4
Here's how it works.
<div>
target1
<span>target2</span>
<span>target3</span>
target4
</div>
When you click target4,
I want to bring the text called target4.
How should I approach it?
html javascript
I'm sharing the answer to the stack overflow.
var div = document.querySelector("div"); // get the div wrapper
div.childNodes.forEach(function(node) { // loop over the nodes
var text = node.textContent; // get the text
if (node.nodeName=="#text" && text.trim()!="") { // if text and not empty
var span = document.createElement("span"); // wrap in a span
span.textContent = node.textContent.trim();
node = div.replaceChild(span,node);
}
});
div.onclick=function(e) {
console.log(e.target.textContent);
}
span { color:red }
<div>
target1
<span>target2</span>
<span>target3</span>
target4
</div>
© 2024 OneMinuteCode. All rights reserved.