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();

55 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

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.

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

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.

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.

IdealAssignmentHelp is one of the best companies that have helped thousands of students in getting their Assignment Help done. Our experts available 24*7. We offer the best platform to the students looking for My Assignment Help companies. If you interested to get assignment then contact our expert team.

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

Get Case Study Help by local Singapore writers at immediate basis from students assignment help.


How do you clean a fabric sofa?

How much does it cost to have a sofa cleaned?

How do you clean a sofa?

Can you get a couch professionally cleaned?

شركة تنظيف كنب بمكة بالبخار




On the off chance that you can't deal with your time for composing your schoolwork, pick the help of scholastic essayists by means of Assignment Writing Service online administrations and achieve your work immediately. Working with various errands limits you to put your 100 % in each undertaking and takes your most extreme hours from every day study schedule. Without a doubt, you have to lead legitimate research and gather applicable data for forming your scholastic papers. On the off chance that you are confronting time shortage, take the task aide's help with Singapore and complete your task without any problem. Peruse the site of specialist organizations and check their administrations cautiously. Various subjects have various specialists and various methods of composing papers. You will get appropriate assistance according to your subject prerequisites. Ensure you associate with a compelling specialist organization of Online task help benefits inside your spending plan.

Hi, I am stella brown I am reading your blog, It is amazing blog thanks for the sharing the blog. Allassignmentservices.com provide the Ecology Assignment Writing Service such as a information about education for students queries. allassignmentservices also provide the Neuroscience Assignment Writing Service. Students from different walks of life can afford our assignment help services as we are affordable. Moreover, our team of academic writers is highly efficient at their work.

Hello, I would like to thank you for sharing this interesting information. I appreciate reading it. The material you have provided here will be useful for a lot of people. I was actually looking for essays professor writing service nevertheless, thanks.

i also have tried to modify this but this was not much easy to modify it as it is publicly defined.

Look at a couple of contemplations coming to adult face mask and perceive how you can in like way re-attempt this force Valentine's Season with kinship and energy to one another with quality and moderate Valentine shirts and custom Valentine face covers.

I've shopped around in numberless Programming Assignment Help websites that have either turned out to be shady or incompetent. You then crossed my way and proved your worth. What amazed me was your considerate prices that are affordable to all students around the globe. Likewise, your pricing criteria are the fairest of all that I've ever seen. Meanwhile, the Python Homework Help tutor was an exceptional one; very fast and extremely knowledgeable.

Miss Me 10mg Tablet for Women Ever Lasting Desire can be used for libido boosting and will give you instant results. You don’t need to worry about any delivery issues. At Omsdelhi, We take extra care of the packaging and deliver it discretely and safely.

Very informative post I really like it. Happy to hear about it more. Taika Waititi Coat

Great job for publishing such a nice article. Your article isn’t only useful but it is additionally really informative. Thank you because you have been willing to share information with us. luxury wedding cars

Is there someone who will do my statistics assignment? Of course, there is. By checking online, you can get the most targeted R programming assignment help from online experienced tutors who will teach you this subject. You will always be able to find a reasonably priced online test helper who will guide you on your statistics learning journey.

Greenhouse urban vertical farming has been largely used in modern agriculture! It helps farmers to withstand climate impacts as well as save land space. Therefore, literally you can yield all year round in the greenhouse. Combined with efficient irrigation systems and various farming equipment , farming become more scientific and successful. Organic farming can even further boost their profit.

Cytomel is a prescription medication used to treat the symptoms of hypothyroidism, an enlarged thyroid gland (nontoxic goitre), myxedema, and myxedema coma. Cytomel can be used alone or in combination with other drugs. Thyroid Products are a family of medications that include T3 cytomel Tablet. Get this tablet from Oms99.

This is one of the top tiger reserves in the nation, with "friendly" tigers and a higher possibility of seeing one here than in many other Indian tiger reserves. Ranthambore also features some of the most diverse flora and animals, making it a must-see destination. Take a short Ranthambore Tour Packages with Go Rajasthan Travel.

Wonderful piece you got here , I feel quite happy after I read your Article because I found out that we still have intelligent informative researchers who can still take time out of their busy schedule to put all this together Do My Assignment I've bookmark your site and furthermore include RSS. keep us refreshed all the time

Hello. Do you provide statistics homework help and math homework help at your stop? I have been looking for it everywhere and I have not been able to get my hands on it. Please tell me if you can assist me with the same so that I can prepare for my college exams. I also want to know how much you charge for economics homework help so please tell me accordingly. Do not delay at all as I am running out of time.

Just click on do my statistic homework for me and see how you get a plagiarism free and professional statistic homework help. The experts are highly experienced in the field of statistics and deliver timely help always. Any improvements are made later also.

It can be nigh on impossible for a visitor or a tourist to navigate through the beautiful and vast city of Melbourne. With South East Luxury service of Luxury tours Melbourne, our professional chauffeurs will aid you in exploring the city to its fullest limits.

Remove Big Boos
Satta Matka Market is the best choice option for you for Matka Market, satta market, DPBoss matka

Great blog. We are here to assists you the best Sports Science Assignment Help across Australia with our best experts. We are working on plague-free content. Also, we are available 24*7 for you at very convenient cost. We are trusted to deliver our service on time.

Nice Blog. You can make you Assignment Help impressive and attractive by our best experts. We are providing multiple assignment help across Uk at very convenient cost. Experts are working on plague-free content and available 24*7 for you.

Are you worried about coming up with ideas for your essay? Or maybe you're having trouble organizing your thoughts into a cohesive argument. Whatever the case may be, Myassignmenthelp.sg offers essay writing help Singapore that can make the process much easier. Their team of writers can provide guidance and support every step of the way.

The Famous Silk Route Tour Package is available near you in a single click. We always behave our customers as our family members. We at Naturecamp Travels are ready to welcome you. So reach us now.

Nice blog
Get university essay writing services Greece at GreeceAssignmentHelp.com. Our qualified writers ensure well-researched and plagiarism-free essays for academic success. Contact us now for reliable assistance!

I love to read this blog... Interesting and informative..

quiebras cerca de mí

Is reckless driving a felony in Virginiathanks for the sharing amazing experience, good site for legal services

Experience paradise with our captivating Holiday Packages to Kashmir. Explore the enchanting beauty of Srinagar, cruise on Dal Lake, and embrace the majesty of snow-clad mountains. Your dream Kashmir getaway begins here. Book now at Lumiere Holidays for an unforgettable journey that will leave you mesmerized.

I wanted to express my sincere gratitude for your blog. Your unique perspective adds a fresh and thought-provoking angle to every subject.Monmouth County Driving Without a License Attorney

Amazing, Your blogs are really good and informative. I got a lots of useful information in your blogs. Instead, you need to retrieve the source from the DOM tree after modifying it, then assign that source back to the variable virginia bankruptcy means test. It is very great and useful to all. Keeps sharing more useful blogs..

Experience the serene beauty of Mount Abu with our bespoke Mount Abu Tour Packages. Nestled in the Aravalli Range, this hill station offers a peaceful escape from the desert heat. Explore lush forests, serene lakes, and historic temples. Let us craft your ideal getaway. Book your Mount Abu adventure at Go Rajasthan Travel and unwind in this picturesque hill station.

I thoroughly enjoyed reading your insightful blog post. Your well-researched content truly resonated with me, i was finding christmas coats and but appreciate the depth of information you provided.

I thoroughly enjoyed reading your insightful blog post. Your well-researched content truly resonated with me, and I appreciate the depth of information you provided. online shopping ladies suit

"Exploring the art of modifying HTML strings using jQuery – this tutorial is a coding gem! 💻🛠️ The step-by-step guidance and clear explanations make it a breeze to enhance web development skills. Kudos to the author for demystifying the process and empowering developers to wield the power of jQuery effectively. Ready to level up my coding game! 👩‍💻🚀 #jQueryMagic #CodingEnthusiast #WebDevelopmentJourney"

Nueva Jersey Violencia Domestica Acto

Post a Comment