1

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?

4
  • Do you have control over the outputted HTML? If it was in an actual label tag, then it would be much easier. Commented May 18, 2016 at 1:38
  • I wish, but unfortunately I do not. I am trying to strip this content off a web page. Commented May 18, 2016 at 1:39
  • What versions of IE are you concerned with? Commented May 18, 2016 at 1:43
  • I am using Chrome. Commented May 18, 2016 at 1:44

3 Answers 3

2

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(':'));
Sign up to request clarification or add additional context in comments.

Comments

1

What about:

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

1 Comment

Thank you for your answer as well!
1

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.

4 Comments

This does not work... child returns a nodeList. Therefore you must target an item within that node list.
thanks, I seldom use getElementsByName, so I take it as getElementById.
Yeah it's not used often anymore. But, usually the method name hints at the returned value. getElement... vs getElements... or querySelector vs querySelectorAll
yes. I turned to querySelector & querySelectorAll once I know how to use them to deal with DOM elements. And they act more like jQuery('selector').

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.