Search code examples
javascriptattributessiblings

Get the id of previous sibling anchor element in javascript


Solved : to get the id of the previous element, use previousElementSibling.id instead of previousSibling.id. Thank you to Xufox and Skyline3000 who quickly provided the solution.


Having some breadcrumbs done of anchors elements, I'm trying to get the id of the previous sibling when one breakcrumb is clicked (i.e. the parent category). eg. Fruits> Apples> Green apples

Unfortunately, my code does not work.

  • alert(this.previousSibling) returns [object Text]
  • alert(this.previousSibling,id) returns id is undefined.
  • alert(this.previousSibling,getAttribute(\'id\') returns TypeError: this.previousSibling.getAttribute is not a function.
  • alert(this.previousSibling,attr(\'id\')) returns TypeError: this.previousSibling.attr is not a function.

I assume that the sibling is not correctly reached as I was expecting some Element or Object and not Text.

Here's what the HTML and javascript of two breadcrumbs look like:

<a id="n5_40_64_40" onclick="javascript:
    var tree=jQuery('#tree').dynatree('getTree');
    if (!tree.activateKey('40')) {
      var parent=0;
      if (1) {
       parent=this.previousSibling.id.split(/[_]+/).pop();
      }
    }
    return false;" href="">Apples</a>
>
<a id="n5_40_64_64" onclick="javascript:
    var tree=jQuery('#tree').dynatree('getTree');
    if (!tree.activateKey('64')) {
      var parent=0;
      if (2) {
       parent=this.previousSibling.id.split(/[_]+/).pop();
      }
    }
    return false;" href="">Green apples</a>

Solution

  • All text and whitespace, including whitespace and new lines between your HTML tags, count as a TextNode. Thus the tag's previous sibling is actual the textNode of whitespace between the <a> tags. What you really want to do is find the previous sibling that is an element (HTML tag).

    For that you should simply use this.previousElementSibling.