Reputation: 113
guess I have this
<td id="c1s2a"><input type="hidden" name="allow_move" value="1"></td>
how can I access the element 'allow_move' referring with the id c1s2a? there are many allow_move named inputs, so I can't use document.getElementsByName("allow_move").
I tried this: document.getElementById("c1s2a").allow_move=0;
but it did not work.
(Yes, I want to change its value)
Upvotes: 2
Views: 4012
Reputation: 11805
There are multiple ways of doing this. Some more efficient than others.
var allow_moves = document.getElementsByName("allow_move");
var index=0;
for(var j=allow_moves.length; index<=j; index++)
{
if(allow_moves[index]&&allow_moves[index].parentNode.id=='c1s2a')break;
}
if(index<allow_moves.length)console.log(allow_moves[index].value);
console.log(document.getElementById("c1s2a").firstElementChild.value);
console.log(document.getElementById("c1s2a").childNodes[1].value);
console.log(document.getElementById("c1s2a").children["allow_move"].value);
//because I like being difficult, and because you never should, here is the regex way
//get the value
console.log(document.getElementById("c1s2a").innerHTML.replace(/([\s\S]*value=\")([^"]*)([\s\S]*)/g,"$2"));
//replace the value
document.getElementById("c1s2a").innerHTML = document.getElementById("c1s2a").innerHTML.replace(/([\s\S]*value=\")([^"]*)([\s\S]*)/g,"$1"+newValue+"$3");
Upvotes: 0
Reputation: 177691
I would have sworn that
document.getElementById("c1s2a").getElementsByName("allow_move")[0].value=0
would work, but as this fiddle shows, it gives Uncaught typeerror for the cell.getElementsByName!!!
Here is an alternative that I am not too happy about
window.onload=function() {
var inputs = document.getElementsByName("allow_move");
for (var i=0, n=inputs.length;i<n;i++) {
console.log(inputs[i].parentNode.id)
if (inputs[i].parentNode.id=="c1s2a") {
inputs[i].value=0;
}
}
}
Upvotes: 2
Reputation: 71908
If you really have just the input tag inside the td (and no other text, whitespace, or tags), you can simply use the following to get a reference to that element:
document.getElementById("c1s2a").firstChild;
To set its value:
document.getElementById("c1s2a").firstChild.value = 0;
There is also a property called firstElementChild
, which ignores text nodes and comment nodes, but unfortunately isn't supported in IE before version 9.
Another option on modern browsers is document.querySelector
, that takes a CSS selector and returns a DOM node. The support table says it's IE8+, but I heard there are some compatibility issues on IE8.
Examples:
document.querySelector("#c1s2a input").value = 0;
or
document.querySelector("#c1s2a input[name='allow_move']").value = 0;
Upvotes: 3
Reputation: 2081
If you cannot rely on the input being the first child, try this:
document.getElementById("c1s2a").children["allow_move"]
See http://jsfiddle.net/KemmU/
Upvotes: 3