javascript - Find parent of a href attribute and access specific property using jquery -


i working on tree view. please check link . has example tree link (just search link enabled, or on page).

if inspect element name child 2, see link this:

enter image description here

i should able search tag href set #child2 , once find that, should find parent (li tag) , access data-nodeis property , return value.

so far able this: $('a[href="#child2"]'); not sure do next.

please

you can use .parents() traverse until find element need:

var nodevalue = $('a[href="#child2"]').parents("li").attr("data-nodeid"); 
  • .parents() when nested several elements deep.

  • .parent() if element direct descendant

    • this work particular situation
  • .closest() work too, traverses upwards, difference closest starts @ element , parents starts @ parent element

see fiddle example using .parents() or snippet below:

var nodevalue = $('a[href="#child1"]').parents("li").attr("data-nodeid");    document.getelementbyid('result').innerhtml = nodevalue;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <ul>      <li data-nodeid="1">          <div><a href="#child1">child1</a></div>                </li>      <li data-nodeid="2">          <div><a href="#child2">child2</a></div>      </li>  </ul>  <div id="result"></div>


Comments