Faouzi FJTech Faouzi FJTech - 1 year ago 103
HTML Question

Find element in document using HTML DOM

I need to be able to select and modify an element in an HTML document. The usual way to find an element using jQuery is by using a selector that selects by attribute, id, class or element type.
However in my case I have the element's HTML DOM and I want to find the element on my document that matches this DOM.

Important :

I know I can use a class selector or ID selector etc.. but sometimes the HTMLs I get don't have a class or an ID or an attribute to select with, So I need to be able to select from the element's HTML.

For example here is the element I need to find :

<span class='hello' data='na'>Element</span>

I tried to use jQuery's Find() but it does not work, here is the jsfiddle of the trial : https://jsfiddle.net/ndn9jtbj/

Trial :

el = jQuery("<span class='hello' data='na'>Element</span>");
jQuery("body").find(el).html("modified element");

The following code does not make any change on the element that is present in my HTML and that corresponds to the DOM I have supplied.
Is there any way to get the desired result either using native Javascript or jQuery?

Answer Source

You could filter it by outerHTML property if you are sure how browser had parsed it:

var $el = jQuery("body *").filter(function(){
   return this.outerHTML === '<span class="hello" data="na">Element</span>';
$el.html("modified element");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download