Question

As I'm iterating through a set of HTML elements passed into a function, I'm trying to set a class on certain elements (rel), depending upon a test. After I set the class, the content I'm returning appears not to have been changed. I'm sure there's a basic disconnect in my logic - any guidance on why my changes don't appear?

this JSFiddle shows it in (in)action: http://jsfiddle.net/spRvh/3/

HTML

<ul> 
      <li title = "ID: 3 " id = "ID1" rel = "departmentgroup" class = "leaf"> 
        <a href = "#" class = "departmentgroup" rel = "15000_3_16010_relationship_Department-Path"> 
            <ins class = "departmentgroup"> & nbsp; </ins>
            Floating
        </a> 
      </li>
</ul>   

jQuery:

newData = $.trim(data);
$.each($(newData).find("a"), function (i, item) {
    thisrel = $(item).attr("rel");
    if ($('#' + thisrel).length > 0) {
        $(item).children().removeClass().addClass('tick');
    }
  });
$.each($(newData).find("a"), function (x, curr) {
    alert($(curr).children().attr("class")); // no changes evident
});
Was it helpful?

Solution

You're getting this issue because you're passing in a HTLM string, not the actual DOM nodes, so you're changing classes on a completely unrelated piece of HTML that has nothing to do with the actual nodes in the document.

To fix it, change

fixit($("#testit").html());

to

fixit($("#testit"));

and modify the function to work with the DOM, not a string you pass in

function fixit(data) {
    $.each(data.find("a"), function (i, item) {
        var thisrel = $(item).attr("rel");
        if ( $('#' + thisrel).length > 0 ) {
            $(item).children().removeClass().addClass('tick');
        }
    });
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top