简体   繁体   English

jQuery解析html并对其进行更改

[英]jQuery parse html and change it

How can I parse an html string in jquery and change a specific element without loading it into the "normal" DOM. 我如何解析jquery中的html字符串并更改特定元素,而不将其加载到“普通” DOM中。

What is not working: 什么不起作用:

  • // 3. the border is applied to any element, not only on the contentContainer element // 3.边框不仅适用于contentContainer元素,还适用于任何元素
  • // 4. the full content is loaded into the #outputContainer and not only the #contentContainer // 4.将全部内容加载到#outputContainer中,而不仅是#contentContainer

This is my .html File: 这是我的.html文件:

<body>
  <h1>Title</h1>

  <div id="outputContainer">
  AAAAAAAAA
  </div>

</body>

</html>

This is my .js File: 这是我的.js文件:

var html = '<!DOCTYPE html> <html> <body>   <h1>HTML DOC</h1> ' 
            + '  <div id="contentContainer">     <ul> ' 
      + '  <li><a href="http://www.google.com">google</a></li> ' 
      + '  <li><a href="http://www.netflix.com">netflix</a></li> ' 
   + '  </ul>   </div> '
   + ' <div><ul><li><a href="http://www.yahoo.com">dont show yahoo</a></li></ul></div>' 
   + '</body> </html> ';


// 1. Parse HTML
var parsedHtml = $.parseHTML( html );

// 2. get contentContainer from parsed html
var contentFromParsedHTML =  $(parsedHtml, "#contentContainer");


// 3. change contentContainer from parsed html
$( contentFromParsedHTML, "#contentContainer").css( "border", "3px solid red" ); // not working

// 4. display changed contentContainer
$("#outputContainer").html(contentFromParsedHTML, "#contentContainer");

You can find this code on js fiddle: https://jsfiddle.net/9ordytj7/ 您可以在js小提琴上找到此代码: https : //jsfiddle.net/9ordytj7/

The method parseHTML returns an array and .css operates on the whole collection. 方法parseHTML返回一个数组, .css对整个集合进行操作。

You can do this: 你可以这样做:

var contentFromParsedHTML =  $(parsedHtml).filter("#contentContainer");
contentFromParsedHTML.css( "border", "3px solid red" );
$("#outputContainer").html(contentFromParsedHTML);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM