eric2323223
eric2323223

Reputation: 3628

How to get parent id by chidren data in jQuery?

I have blow HTML, I want to write a function that could get id of the anchor tag by its child record and the record index. It should looks like this:

getLinkId("100", 0)=300001
getLinkId("RD", 1)=300001
getLinkId("PD", 1)=300002
getLinkId("902", 2)=300002

I think jQuery might help to implement, but I am not quite familiar with it. Could anyone help me?

<ul id="listview_Sample">
    <li role="option">
    <div class="ui-btn-inner ui-li">
    <div class="ui-btn-text"><a href="" class="listviewLines" id="300001">
    <div class="lv_lines" id="300001">
    <div class="lv_line">
    <div class="lv_line_field">100</div>
    </div>
    <div class="lv_line">
    <div class="lv_line_field">RD</div>
    </div>
    <div class="lv_line">
    <div class="lv_line_field">501</div>
    </div>
    </div>
    </a></div>
    </li>
    <li role="option">
    <div class="ui-btn-inner ui-li">
    <div class="ui-btn-text"><a href="" class="listviewLines" id="300002">
    <div class="lv_lines" id="300002">
    <div class="lv_line">
    <div class="lv_line_field">200</div>
    </div>
    <div class="lv_line">
    <div class="lv_line_field">PD</div>
    </div>
    <div class="lv_line">
    <div class="lv_line_field">902</div>
    </div>
    </div>
    </a></div>
    <span class="ui-icon ui-icon-arrow-r"></span></div>
    </li>

Upvotes: 0

Views: 143

Answers (2)

Richard Dalton
Richard Dalton

Reputation: 35793

I think this should work.

function getLinkId(id, index){
    var matchedResult = $('div.lv_line_field:contains("' + id + '")');

    if (matchedResult.parent().index() == index)
        return matchedResult.closest('a.listviewLines').attr('id');

    return null;
}

http://jsfiddle.net/4KezR/

Can even do it all in one line:

function getLinkId(id, index){
    return $('div.lv_line_field:contains("' + id + '")').filter(function() {
        return $(this).parent().index() == index;
    }).closest('a.listviewLines').attr('id');
}

Upvotes: 2

Rob W
Rob W

Reputation: 348962

This function meets your wishes for this specific case. See the comments for an explanation of each line:

function getLinkId(id, col){
    var main = document.getElementById("listview_Sample");

    //enumerate through all list items
    for(var i=0,len=main.getElementsByTagName("li").length; i<len; i++){

        //Each list item contains 3 .lv_line_field elements.
        // Compare the content of the (i*3+col)th element.
        if(main.getElementByClassName("lv_line_field")[i*3+col].textContent == id){

            //match found, return id.
            return document.getElementsByClassName("listviewLines")[i].id;
        }
    }
}

Upvotes: 2

Related Questions