This question is about Sergey Ilinsky's jQuery XPath plugin. I have an xml file which I navigate it through this plugin. The file itself is not important to see. The question is more related to functionality of the plugin.
var elemList = $(xmlDoc).xpath("call-script/option" + xpathExtension);
for (var i = 0; i < elemList.length; i++) {
if (elemList[i].getAttribute('text') != null) {
alert(elemList[i].getAttribute('text'));
//elemList[i].getAttribute('text') = 'example';
}
}
I would like to set the text attribute of the selected node as shown in commented out line. getAttribute
works like a charm when I use it only for reading purposes. I would like to assign it with some kind of a setAttribute
function which is not available. Any help from you would be much appreciated.
Plugin's link: http://plugins.jquery.com/xpath/
Plugin's version: 0.2.4
Edit: I think I should share part of my xml to give a better understanding.
<?xml version="1.0"?>
<call-script say="Good morning">
<option text="caller asks for blah">
...
...
...
</option>
<option text="caller requests blah">
...
...
...
<option text="caller would like to blah">
...
...
...
</option>
</call-script>
You've already got jQuery, so you can be a little more efficient if you use jQuery's .attr()
function, which does double-duty as both a getter and setter depending on the arguments. The $.each()
function can be used here as well.
Rewriting your sample:
$.each(elemList, function(key, element) { // iterate over each thing in elemList
if (element.attr('text') !== null) { // without 2nd argument, just returns the value
alert(element.attr('text')); // same
element.attr('text', 'example'); // with 2nd argument, sets the value
}
});
Looks like there is a setAttribute
function as well.
elemList[i].setAttribute('text','example');
This has fixed my problem. Sorry for hassling you.
Tutorial link: http://www.w3schools.com/xml/met_element_setattribute.asp
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.