我需要在加载用户信息的网页上测试特定的InterHTML字符串。我的问题是,此元素的位置[14]根据是否存在的其他帐户详细信息而变化。(即有时此InnerHTML是[15]或[16])InnerHTML除了类名称" style16"以外没有其他标识符。
moreso innerhtml每个帐户之间都会发生变化,因此我需要测试其值。
我是否需要创建某种VAR来引用此元素位置?如果是这样,我该怎么做。
这是HTML:
<tr>
<td class="style16">Zip:</td>
<td>12345</td>
</tr>
<tr>
<td class="style16">CountryCode:</td>
<td>TH</td>
</tr>
我是DOM和JavaScript的新手,如果这令人困惑,则很抱歉。
预先感谢
您可以在 jQuery
中的同一类的所有元素循环:
$('.style16').each(function(i, obj) {
var innerHTML = $(this).next().text();//next returns the next 'td' sibling
});
这样,您可以跟踪所有要寻找的InnerHTML元素。
function find(elem){
if(elem.innerHTML=="TD"){
return elem;//found elem lets return
}
for(child of elem.childNodes){
if(var a=find(child)){
return a;//a child of child of child... is the searched one, so return it
}
}
return false;//nothing found
}
这样使用:
window.onload=function(){
elem=find(document.body);
if(elem){
// now you can use elem until it is destroyed...
elem.innerHTML="found this";
}else{
alert("Sorry doesnt exist");
}
}
注意:循环槽的DOM越大,则需要的时间越长。因此,为了提高性能,可以从包含搜索搜索的父元素开始
如果您知道父元素的类,则可以执行此操作:
var elems=[...document.getElementsByClassName("style16")];
var elem=false;
var found=elems.some(function(el){
if(el.parentNode.childNodes[1].innerHTML=="TD"){
elem=el.parentNode.childNodes[1];
return true;//kill execution
}
});
if(found){
console.log(elem);
}else{
alert("not found");
}