0

I'm using AJAX to receive an XML response, which I then need to manipulate. By using jQuery's context option, I can select from the XML data, but I am still unable to write to it.

$('blah', xml)

selects xml just fine, but

$('blah', xml).removeClass( 'myClass' )

seems to do nothing to the xml variable! How can I achieve the functionality I'm looking for?

Example:

var data = null;

$(document).ready(function(){
$.ajax({
   type:"GET",
   url:"blah/blah.jsp",
   success:function(msg)
   {
      data = msg;
      init();
   }
});

function init()
{
   $('#myElement', data).removeClass('hidden');//removeAttr('class') also fails
}

Example xml file:

<root>
<div>
<!--lots of content -->
</div>
<div>
<p id = "myElement<->" class = "hidden">
  Test!
</p>
</div>
</root>
2
  • May we see the XML file? Commented Sep 28, 2009 at 21:16
  • addClass/removeClass are HTML specific, they modify the attribute named class. Can you tell us if removeAttr works? Commented Sep 28, 2009 at 21:25

1 Answer 1

1

This works for me.

<html>
<head>
  <title>Test Page</title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
    <script type="text/javascript">
    $(function()
    {
    var data = null;
    $.ajax({
        type:"GET",
        url:"sample.xml",
        dataType: 'xml',
        success:function(msg)
        {
           init( $(msg) );
        }
    });

    function init( $xml )
    {
      var $myElement = $xml.find( '#myElement' );
      $myElement.removeAttr( 'class' );
      console.log( $myElement );
    }
    });
    </script>
</head>

<body>

</body>
</html>

And here's sample.xml

<?xml version="1.0" encoding="UTF-8"?>
<root>
<div>

</div>
<div>
<p id = "myElement" class = "hidden">
  Test!
</p>
</div>
</root>

so make sure you are requesting with "xml" as the dataType option, and that your JSP page returns the content with the correct Content-Type header (text/xml)

Sign up to request clarification or add additional context in comments.

2 Comments

repeatedly clicks up vote, hoping it might shoot to 100. Content-type on a jsp response header. What a subtle bug.
Also be aware of the possibility of needing to use msg.d instead of just msg. encosia.com/2009/02/10/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.