0

There is html on the screen that looks like this.

screen:

target1 target2 target3 target4

code:

<div>
  target1
  <span>target2</span>
  <span>target3</span>
  target4
</div>

When i click on target4, I want to get the text "target4"

How do you approach it?

3 Answers3

1

you can get the value of your last text node, this is not a problem. Unfortunately :

childNodes may include text nodes, which don't support event handlers

var x = document.getElementsByTagName("div")[0];
x.addEventListener("click",function(e){
  console.log(e.currentTarget.childNodes[4].textContent)});
<div>
  target1
  <span>target2</span>
  <span>target3</span>
  target4
</div>
scraaappy
  • 2,830
  • 2
  • 19
  • 29
  • he want to show target4 when click on target4 only. – Saranya Rajendran Mar 23 '18 at 09:10
  • When i click on target4, I want to get the text "target4" ==>this one does not solve this – Athul Nath Mar 23 '18 at 09:11
  • 3
    Read the answer. `target4` is a text node and cannot have an event listener added to it. The OP can wrap your text in a span, attach an event listener to the div and capture it with `event.target`, but with the current markup what the OP is asking is not possible. If this isn't possible this is really the only solution. – Andy Mar 23 '18 at 09:13
1

This answer both questions you had

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>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

scraaapy has answered your question. But if you have the control over the HTML, then just do this:

HTML

<div>
  <span>target1</span>
  <span>target2</span>
  <span>target3</span>
  <span>target4</span>
</div>

JavaScript

var el = document.querySelector("div");
  el.addEventListener("click", (e) => {
  console.log(e.target.textContent);
});

This way, your code is much easier to maintain and work with. Hope this help!

Joshua
  • 3,055
  • 3
  • 22
  • 37