2012-12-22 34 views
0

我想让我的脚本只改变一个页面上的元素样式。我想也许最好的方法是检测并查看页面是否有唯一的ID(profile-advanced-details),如果有,则将其他ID(page-body)高度修改为1500px。Javascript:如果一个类存在,我如何修改类的属性?

我试过这个,但它似乎不工作...是我的语法错误?还是有更好的方法来做到这一点?

var wrap = document.getElementById("page-body"); 

if (!document.getElementsById('profile-advanced-details').length){ 
    return; //if profile-advanced-details doesn't exist, do nothing 
} 

else { 
    wrap.style.height = "1500px";//if it does exist, change the height of page-body 
} 

谢谢!

+0

如果(的document.getElementById( '轮廓先进-细节')。长度<= 0){} – algorhythm

回答

0

id s是独特的。没有这样的方法,如document.getElementsById()。改为使用document.getElementById(),它将返回指定的idnull的元素。

0

getElementById是单数,不是复数。你也不需要.length,因为它意味着不同的节点。

if(document.getElementById('profile-advanced-details')) { 
    document.getElementById('page-body').style.height = "1500px"; 
} 

您可能还可以使用CSS,但前提是参考要素(“型材先进范围”)为目标之前(“页体”)。这可能不是这里的情况,但它是一个很好的把戏知道:

#profile-advanced-details + #page-body, 
    #profile-advanced-details + * page-body {height:1500px} 
/* the following may work in CSS4: */ 
!#page-body #profile-advanced-details, 
    !#page_body + #profile-advanced-details, 
    !#page_body + * #profile-advanced-details {height:1500px} 
$#page-body #profile-advanced-details, 
    $#page_body + #profile-advanced-details, 
    $#page_body + * #profile-advanced-details {height:1500px} 
#page-body! #profile-advanced-details, 
    #page_body! + #profile-advanced-details, 
    #page_body! + * #profile-advanced-details {height:1500px} 
#page-body$ #profile-advanced-details, 
    #page_body$ + #profile-advanced-details, 
    #page_body$ + * #profile-advanced-details {height:1500px} 
/* The different ones are partially because I don't remember the spec, 
      but mostly because it's changing */ 
0

你应该能够做到

var wrap = document.getElementById("page-body"); 

if (document.getElementById('profile-advanced-details')){ 
    // profile-advanced-details does exist 
    wrap.style.height = "1500px"; 
} 

这工作,因为“轮廓 - 高级 - 详细信息”中的getElementById如果它不存在,将返回null,这意味着条件不计算为真,其中的代码不会被调用。

+0

因为不幸的是我不能直接修改的HTML。我只能添加将在所有页面上显示的脚本和CSS。 – teeth

+0

在这种情况下,上述方法可行,但如果您有多个具有相同ID的元素,我认为其他人提到您确实应该使用类名称。然后你可以使用函数'getElementsByClassName'。但为了记录,如果您有多个具有相同ID的元素,则'getElementById'应该返回找到的第一个元素,但不要依赖于此,因为它不应该完成。 – Ally

0

由于元素ID是唯一的,你倒是应该给你的元素的类名'profile-advanced-details',用document.getElementsByClassName检查,如果一个与你提供的这个woiuld看起来像这样的代码存在

所以:

var wrap = document.getElementById("page-body"); 

if (document.getElementsByClassName('profile-advanced-details').length == 0){ 
    return; //if profile-advanced-details doesn't exist, do nothing 
} 

else { 
    wrap.style.height = "1500px";//if it does exist, change the height of page-body 
} 
0

你说班,对吗?然后改变

  if (!document.getElementsById('profile-advanced-details').length) 

  if (!document.getElementByClass('profile-advanced-details').length) 
相关问题