I want to get text when I click on a specific area in HTml as follows.

Asked 2 years ago, Updated 2 years ago, 17 views

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

2022-09-22 19:43

1 Answers

I'm sharing the answer to the stack overflow.

https://stackoverflow.com/questions/49445686/how-to-get-text-values-when-click-if-text-are-not-inside-html-tag

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>


2022-09-22 19:43

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.