开发者

Select label from document without knowing id

I've been working on the modification of an iframe using javascript. The iframe contains this form

What I want to be able to do is retrieve information from the label; however it doesn't have an ID. is there any way I could get javascript to get the input button by ID, a开发者_StackOverflow社区nd have it analyze the label assigned to it?


You could go through all label elements and find the one whose for attribute matches your button ID:

var labels = document.getElementsByTagName('label');
var label = null;
var buttonID = '...';
for (var i = 0; i < labels.length; i++)
  if (labels[i].htmlFor == buttonID) {
    label = labels[i];
    break;
  }
// "label" now refers to the label you're looking for


casablanca's way is the best way if you only know the button ID.

Depending on what else you might know, other things might be quicker. If, for instance, you know that it is inside a DIV that you know the ID of, and you know that it is the only label inside that DIV, then you could do something like

var label = document.getElementById('myDiv').getElementsByTagName('label')[0];

If you know that it'll always be the only label with the same parent as your button, you could write

var label = document.getElementById('button').parentNode.getelementsByTagName('label')[0];

Basically, a broad set of solutions might be optimal depending on what assumptions you can afford to make. If you only know what you've told us in the question, then casablanca's iteration is the way to go.


I highly recommend investigating jQuery for this sort of manipulation. I'm sure that you probably don't want to introduce a whole Javascript framework to solve this one little issue, but if you learn it you will find that Javascript programming becomes much easier.

Assuming that @casablanca's answer is correct, you could accomplish the same thing in jQuery with the following code:

var label = $('label[for="..."]').get(0);

(Or something like that. My syntax may be off. :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜