简体   繁体   中英

Accessing Text Label Value Javascript

Currently, I have a piece of java script that makes a table of cells where each cell has an ordered list of its number, a label, and a text box. A snippet of this code is written below:

<table id="drawAllQuestionsTbl">
<tbody><tr><td class="tbl">
<ol start="1">
<li>Sport 1:&nbsp;<input type="text" name="tq_g_0_guess" size="15"></li></ol></td></tr><tr><td class="tbl">

For brevity, I cut a lot of the extra stuff. In reality, this table is filled with around 10 replicas of this cell, where each cell has an ordered list with a label and text box. For the text box in this ordered list for instance, I can successfully access its value using document.getElementsByName("tq_g_0_guess") . However, my question is how to get the value of the label "Sport 1" next to this text box. Any ideas?

The following will give you the text of the li node. This will be Sport 1: .

var elParent = document.getElementsByName("tq_g_0_guess")[0].parentNode;
var labelText = elParent.innerText;
console.log(labelText); // Sport 1: 

You can leverage labelText to further format the text to the desired result.

If you only want Sport 1 , then you can substring the everything up to the colon

labelText.substr(0, labelText.indexOf(':'));

关于什么:

document.getElementsByName("tq_g_0_guess")[0].parentNode.innerText

writing in JavaScript:

var child = document.getElementsByName("tq_g_0_guess")[0]; // ok, must add a [0] after this.
var preTextNode = child.previousSibling;
var textContent = preTextNode.textContent; // this is the text you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM