How to modify the elements in an html string before appending

♀尐吖头ヾ 提交于 2019-12-08 06:28:12

问题


Maybe I oversimplified my question in https://stackoverflow.com/posts/20577488/ I left out an important intermediate step. I wanted to:

  • create a Javascript string x
  • assign x to a jQuery object (right term?)
  • perform jQuery stuff on this object
  • then append it

    var x = "<p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p> ";
    var template = $(x);
    template.find('p').attr('class','something');
    template.appendTo( ".inner" );   
    

回答1:


You need to use filter instead of find. What you are looking for is at the root level so you need to use filter since find will look for descendants of p that are at the root level. Also you can use addClass to add a class unless you want to remove the existing classes.

var x = "<p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p><p>Test</p>";
var template = $(x)
template.filter('p').attr('class','something');
//Or you can use 
//template.filter('p').addClass('something');
template.appendTo( ".inner" );  

Demo



来源:https://stackoverflow.com/questions/20577616/how-to-modify-the-elements-in-an-html-string-before-appending

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!