Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get text from nested span when li is clicked, with simple javascript

I don't get jQuery yet, so javascript please. I need help adjusting my JS so it gets text from a nested span inside an li when clicked. i have it working now if you click the text, but id like it to work if you click the entire li without it getting the other nested elements (the image).

right now im working with the following html and js:

HTML:

<ul><li><img><span onclick="myfunction(this)">TEXT</span></li></ul> 

<input id="iSupervisorUserName" name="OBKey_WF_Manger_Supervisor_1" type="text" />

JS:

function myfunction(span) {
    var textInsideLi = span.innerHTML;
    var field = document.getElementById("iSupervisorUserName");
    field.value = textInsideLi;

I would like the text from SPAN to be written to the input when the li is clicked, not just the span. I know I should move the onClick call from the span to the li, but how do I adjust the JS so it get only the text inside the span and not the IMG as well?

like image 547
PhilD Avatar asked Dec 19 '13 10:12

PhilD


People also ask

Can we use innerHTML in span?

The innerHTML property returns: This element has extra spacing and contains <span>a span element</span>. The textContent property returns: This element has extra spacing and contains a span element.

Can you have nested span tags?

The HTML span TagYou shouldn't nest span unless you thoroughly know what you're doing – but you can put multiple span tags within a block-level element.

Can you use span in JavaScript?

The <span> tag is an inline container used to mark up a part of a text, or a part of a document. The <span> tag is easily styled by CSS or manipulated with JavaScript using the class or id attribute.


2 Answers

here you go

html

<ul><li onclick="myfunction(this)"><img><span>TEXT</span></li></ul>

js

function myfunction(li){
 document.getElementById("iSupervisorUserName").value=
 li.getElementsByTagName('span')[0].textContent;
}

or

function myfunction(li){
 document.getElementById("iSupervisorUserName").value=
 li.childNodes[1].textContent;
}

anyway i would add an eventlistener to the ul or the li's.. as inline js is a mess if you wanna update the code later.also there is alot more code generated if you add onclick="myfunction(this)" on each li.

like image 189
cocco Avatar answered Nov 03 '22 15:11

cocco


You may get the inner <span> element with .getElementsByTagName() method:

HTML:

<ul><li onclick="myfunction(this);"><img><span>TEXT</span></li></ul>

JavaScript:

function myfunction(li) {
    var span = li.getElementsByTagName('span')[0],
        textInsideLi = span.textContent || span.innerText,
        field = document.getElementById('iSupervisorUserName');

    field.value = textInsideLi;
    // ...
}
like image 1
VisioN Avatar answered Nov 03 '22 14:11

VisioN