Modifying HTML strings using jQuery

jQuery makes it very easy to modify a DOM tree.  For example, to strip all hyperlinks (<a> tags) from an element, we can write (demo)

$(...).find('a[href]')
      .replaceWith(function() { return this.childNodes });

After getting used to this, one might want to use jQuery to modify HTML contained in a string.  Here, however, the naïve approach does not work:

var htmlSource = ...;
$(htmlSource).find('a[href]')
      .replaceWith(function() { return this.childNodes });

This code tries to remove all <a> tags from the HTML contained in the htmlSource string.  However, what it actually does is create a detached DOM tree containing the new elements, strip all <a> tags in those elements, and throw the whole thing away.  It doesn’t modify the original string.  In fact, since the  $ function only takes a reference to an immutable string, this approach cannot modify the original string.

Instead, you need to retrieve the source from the DOM tree after modifying it, then assign that source back to the variable. 

There is an additional subtlety with this approach.  jQuery cannot return the complete HTML source for a collection of elements.  Therefore, it is also necessary to wrap the HTML in a dummy element (typically a <div>).   One can then call .html() to get the innerHTML of the dummy element, which will contain exactly the desired content

This also eliminates the distinction between root-level elements and nested elements.  If the original HTML string contains root-level <a> elements (which aren’t nested in other tags), writing $(htmlSource).find('a') won’t find them, since .find() only searches the descendants of the elements in the jQuery object.  By wrapping the HTML in a dummy element, all of the elements in the original content become descendants, and can be returned by .find().

Here, therefore, is the correct way to modify an HTML string using jQuery:

var htmlSource = ...;
var tree = $("<div>" + htmlSource + "</div>");

tree.find('a[href]')
    .replaceWith(function() { return this.childNodes });

htmlSource = tree.html();

20 comments:

THANK YOU GOOD SIR!!!

yea!!

old but gold

Such descriptions are important. Eve

I advise you to read these advices before writing your response paper. Here you can find some important tips

Engineers who wish to migrate to Australia must submit a Competency Demonstration Report and the Engineers Australia must approve it. Thus, engineering students look forward to getting Cdr Australia which assists them to get a flawless CDR. This reduces the chances of rejection by the EA. Choose Myassignmenthelp.com.
Most students and experienced civil engineers are today looking forward to migrating to Australia as the job scope is better and bigger with a high pay scale. Therefore, getting CDR help is the only scope to gain entry into the country.
The CDR for Engineers Australia must be impressive and abide by the ANZSCO code and guidelines. It should also showcase the skills of the applicants as a suitable civil engineer to work according to the Australian rules and regulations.
The service providers who assist the students with CDR have experienced CDR report writing expert. These writers know the requirements of a CDR and do it accordingly.


Livewebtutors aims at providing the students with a one stop solution for all the academic related issues. The company has Livewebtutors is an online Assignment Help and assignment writing service offering expert assignment help. Hire Australian assignment writing experts.
visit now:- Assignment Help

My assignment help team associated with AllAssignmentHelp.com/au/ is ready to serve you with your academic papers. Either it is complex work for you or you have no time to complete it on time, our team of writers is ready to deliver the project on time along with maintaining the high-quality in the delivered work.

Nice blog. Online assignment help service in Australia offering top-notch and original Assignment Help with quality results at an amazing price.
My Assignment Help

We provide Online Assignment Help support. Our writers have simplified your assignment so that you can resolve questions about assignments.

Assignment Help is the best answer to solve all the problems related to assignment writing and project submission. Make your work more effective and valuable with the help of academic experts of greatassignmenthelp For any help, talk to academic expert.
Assignment Help Online

Studies show that around 56% of all students consider their homework as the most primary source of stress in their life. It is no wonder then these students constantly think of ‘who can do my homework ’ in UK. Fortunately for them, we provide expert homework help at very reasonable prices. Recent research has also revealed that on average students between the ages of 6 to 17 have to spend a little more than three and a half hours each day of their school life doing homework. Our aim is to cut the time you spent doing your homework by more than a half by offering homework online services in UK to students. We offer you with several extraordinary benefits that make us the best choice for you. Homework help uk

personal statement writing
ghostwriter
coursework help

Thanks for sharing the information! Finance has always been one of the most required after programs in education as it can be connected with everything. Top experts also suggest in their finance assignment help that students need to conduct proper research before writing their assignments as they need to find factually correct data and statements for their assignments.

Australia assignment writers for students help you just look at the Assignment help given by the assignment experts. Opting for our Assignment Help Online could be ideal for such students and they can get a complete assignment solution from us. Hire Now!

SingaporeAssignmentHelp.com offers exceptional homework help sg services to all its customers 24x7. Our experts homework helper work hard and put a lot of efforts in completing your university task and make you score high grades.

Thanks for sharing.Get the huge discounted translation help from native translators team of Singapore translation services.Our high experienced Singapore translators team, not software, translates your document 24 X 7 with 100% accuracy.

StudentsAssignmentHelp.com offers Do My Assignment Services to the students of the Uk, USA, Canada and Austraila at the best afffordable price. Our aim to provide best service in minimal price. Get your order now with 10% discount. For more information Contact here- info@studentsassignmenthelp.com or here +44-755-536-9184.

Hi, this is a nice blog thanks for sharing the Informative blog. my assignment help provide the mba essay writing singapore for a assist to student queries. Our writers conduct thorough research to provide you with a flawless sample of mba essay writing singapore. My Assignment help brings do my Consumer Behavior assignment .Writing an elaborate do my Consumer Behavior assignment is anything but easy and most students lack the tenacity to work on the details accurately. If you get the more details Please visit the site through Link.

Post a Comment