I am very new to this concept and struggling to achieve the below requirement.
I have the below xml object in my javascript variable named "detailJSTotal".
<response>
<div>
<p>
<label>
ID:
</label>
812161
</p>
<p>
<label>
Name:
</label>
252
</p>
<a href="javascript:void(0)" onclick="text4.xml">
more...
</a>
</div>
<div>
<p>
<label>
ID:
</label>
812162
</p>
<p>
<label>
Name:
</label>
252
</p>
<a href="javascript:void(0)" onclick="test2.xml">
more...
</a>
</div>
<div>
<p>
<label>
ID:
</label>
812163
</p>
<p>
<label>
Name:
</label>
252
</p>
<a href="javascript:void(0)" onclick="text.xml">
more...
</a>
</div>
<div>
<p>
<label>
ID:
</label>
812164
</p>
<p>
<label>
Name:
</label>
252
</p>
<a href="javascript:void(0)" onclick="test1.xml">
more...
</a>
</div>
Here root element (response) contains multiple < div > elements. Each < div > element contains < label > element and it's value and < a > element.
My requirement is to get the value of < a > element's "onclick" attribute for a given < label > 'ID' value of a < div > element.
Example:
I may want to get the value of "onclick" attribute of < a > element by providing the ID < label > value as '812161'. The return value should be "text4.xml" in the example above.
Just load your xml via jQuery:
var $xml = $(detailJSTotal);
You can now use jQuery all jQuery-functions and select all information you need. For example use find()
:
var $label = $xml.find('label:contains("test")');
return $label.next('a').attr('onclick');
Note: Untested and just written out of my head.
Try Jquery's xmlParser
; like this
var detailJSTotal= `<response> <div> <p> <label> ID: </label> 812161 </p> <p> <label> Name: </label> 252 </p> <a href="javascript:void(0)" onclick="text4.xml"> more... </a> </div> <div> <p> <label> ID: </label> 812162 </p> <p> <label> Name: </label> 252 </p> <a href="javascript:void(0)" onclick="test2.xml"> more... </a> </div> <div> <p> <label> ID: </label> 812163 </p> <p> <label> Name: </label> 252 </p> <a href="javascript:void(0)" onclick="text.xml"> more... </a> </div> <div> <p> <label> ID: </label> 812164 </p> <p> <label> Name: </label> 252 </p> <a href="javascript:void(0)" onclick="test1.xml"> more... </a> </div></response>`; xmlDOM = $( $.parseXML( detailJSTotal) ); function getAttrForID(id){ console.log($($(xmlDOM).find("p:contains(" + id + ")").siblings("a")[0]).attr("onclick")); return $($(xmlDOM).find("p:contains(" + id + ")").siblings("a")[0]).attr("onclick"); } console.log(getAttrForID("812161"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.