获取单击元素父节点的数组编号

时间:2014-10-01 01:48:05

标签: javascript html arrays dom

我需要能够单击按钮并返回其父项数组,以便我可以将样式仅应用于具有相同类名的多个div中的一个,我想在vanilla javascript中执行此操作(如果可能)

    <div class="contentBox">
            <button onclick="expand()" class="contentBoxButton"> + </button>
            <title>Lorem Ipsum Here</title>
            <p> 
                Lorem Ipsum HereLorem Ipsum HereLorem Ipsum HereLorem Ipsum HereLorem Ipsum 
            </p>
        </div>
       <script>
         function expand(){
            var button = document.getElementsByClassName('contentBoxButton');
            var parent = button.parentNode;
            parent.style.height = '200px';

        }
       </script>

2 个答案:

答案 0 :(得分:1)

感谢Felix Kling对.parentNode 的评论

您没有获得单个元素的原因是因为您开始通过其类访问单击的按钮。
var button = document.getElementsByClassName('contentBoxButton');
..确实会为你提供该类所有元素的节点列表 因此,在此之后对行中的parentNode的调用将不起作用,或者结果是所有父项的另一个列表..


这就是你需要它的工作原理:

小提琴:http://jsfiddle.net/13pkrabq/3/


HTML

<div class="contentBox">
    <button onclick="expand(this)"> + </button>
    <p>
        Text Text Text 
    </p>
</div>

<强> JS

function expand(btn) {
    btn.parentNode.style.height = "200px";
}

<强> CSS

.contentBox {
    background-color:#777777;
}

(我添加了CSS以使contextBox可见)

答案 1 :(得分:0)

如果它是您要扩展的div,请考虑将听众放在上面,这样您就不必去寻找。使用 this 传递对div的引用,然后使用按钮值打开或关闭div。

在&#34; +&#34;之间切换按钮的值和&#34; - &#34;同时使用类来应用CSS:

<div onclick="expand(this)">
  <input type="button" value="+" class="expandContentButton">
  <span class="title">Foo bar</span>
  <p class="contentPara">here is the content</p>
</div>

<script>
  function expand(el) {
    var cb = el.querySelectorAll('.expandContentButton')[0];
    if (cb == event.target || cb == event.srcElement) {
      el.className = cb.value == '+' ? 'open' : 'closed';
      cb.value = cb.value == '+' ? '-' : '+';
    }
  }
</script>

和一些CSS:

<style type="text/css">
  .title {
    font-weight: bold;
    font-size: 150%;
  }
  .open {}

  .closed {
    height: 30px;
    overflow: hidden;
  }

  .expandContentButton {
    text-align: middle;
    width: 3em;
  }
</style>