rajnish
rajnish

Reputation: 3

How to convert a Jquery object to string?

I am creating a table using tag. I'm able to catch the element but not able to convert it into a string and perform the conditional check. Please help!!

$(document).ready(function(){
    $('#user tr').each( function(){
           //add item to array
        var value = $(this).find(".user1").html();

        /********* want to do something like 

     if (value == "Y") {
       //apply a class
     }
     *************/

        });

Upvotes: 0

Views: 618

Answers (4)

ZanderKruz
ZanderKruz

Reputation: 106

The html() method of jquery only grabs the inner html of an element. The best way to grab the actual html of an element would be to use

element.outerHTML;

to do that though you have to actually have be manipulating the dom element and not the jquery object.

for example you would do something like this

var html = $(this).find(".user1").get(0).outerHTML;

That will return ALL of the html as a string though, including its contents, not just its HTML of the tags. So if you just want the element HTML, I would clone the element and empty its HTML content.

var tag = $(this).find(".user1").clone().html('').get(0).outerHTML;

Upvotes: 0

Priyank Patel
Priyank Patel

Reputation: 3535

Use .get() method of jquery.

var value = $(this).find(".user1").get(0);

Now u can perform any condition check .

Upvotes: 1

Tiago Peczenyj
Tiago Peczenyj

Reputation: 4623

If you need the html, the find returns a collection of results, try to produce a find query very specific and pick the first

var html = $(this).find(".user1").first().html();

But you can use addClass in this case, is much more effective.

Upvotes: 1

robrich
robrich

Reputation: 13205

if (value === "Y") {
    $(this).find(".user1").addClass("a-class");
}

Upvotes: 2

Related Questions