Eduard Luca
Eduard Luca

Reputation: 6602

Compare 2 elements in jQuery (by content)

So, I have a page with messages. I'm using jQuery.load (requesting the exact same page) to refresh the page smoothly once every X seconds.

The problem is that if there are images on the page, they get reloaded.

So basically what I want to do, is to still use the load method, but to only update the changed elements.

Is it possible to compare jQuery('.message-wrapper').first() with jQuery('.message-wrapper').last() and if they have the exact same structure / content, it should return true. Right now if you compare 2 HTML nodes (so JS, not jQuery), you get true only if they are one and the same element.

What I want to do is check the content to see if it's different.

Disclaimer: I've seen a few similar questions, but none have a working solution.

Upvotes: 3

Views: 6021

Answers (1)

adeneo
adeneo

Reputation: 318182

To compare the text content of your elements you can use text(), or to compare the markup, use html() :

$('.message-wrapper').first().text() == $('.message-wrapper').last().text()

To remove spaces before and after the string, which can be an issue sometimes, you can wrap it in jQuery's $.trim method :

$.( $('.message-wrapper').first().html() ) === $.( $('.message-wrapper').last().html() )

Upvotes: 4

Related Questions