Home >Web Front-end >JS Tutorial >How to convert string into jquery object
This time I will explain in detail how to convert a string into a jquery object, and what are the precautions for converting a string into a jquery object. The following is a practical case, let's take a look.
jQuery(test)[0].outerHTMLouterHTML 是部分浏览器提供的原生DOM属性,可返回包括元素本身在内的html代码。 如果不需要标签本身,可用jQuery的html方法来获取html文本 jQuery(test).html() var test='<p>.<img src="oldsrc" />.</p>' var jObj=$(test); var imgs=jObj.find('img'); imgs.each(function(){ $(this).attr('src','newsrc'); }); test=jObj[0].outerHTML; 或者 test='<p>'+jObj.html()+'</p>'; 这里只能用DOM片断来做,无法带上html
Or you can directly use regular expressions to replace
'<p><img src="oldsrc" /></p>'.replace( /<img(\s+[^>]*)src="([^"]+)"([^>]*)>/ig, function(a,b,c,d){ //这里a代码匹配到的一个img元素的整个字符串,b代码第一个括号内的内容,c代码第二个括号的内容,就是img的src,d代码后面的内容 //这里可以处理下c再连接,也可以直接写新的src return '<img'+b+'src="'+'new src'+'"'+d+'>'; })
or like this:
var a='<p>123</p>'; var jObj=$(a); console.log($('<input></input>'))
Related recommendations:
How to convert html string into Jquery object or Dom object in JavaScript
Conversion between json string and object-javascript/jQuery
Convert jQuery object into ordinary string
The above is the detailed content of How to convert string into jquery object. For more information, please follow other related articles on the PHP Chinese website!