迭代所有html元素并修改内容

时间:2015-09-16 04:46:20

标签: javascript jquery html

我正在使用一个项目,该项目需要对外部html文件的每个元素进行迭代,并使用内部标记修改内容。

我想要一个递归的java脚本函数,它将迭代所有DOM元素并通过在开头和结尾附加#来修改每个内部标记内的内容。

<html>
    <head>
    </head>
    <body>
        <h1>Hello</h1> 
        <div id="something"><span><h1>Hello Folks!</h1></span></div>
        <span>Lovely lady</span>
        <div id="name">
            <div class="random">
                <div><span>0</span></div>
                <div><span>1</span></div>
            </div>
        </div>
        <div class="detail ">
            <div class="">Process</div>
            <div class="page">4 of 6</div>
            <div class=" ">
                <div class="float-left">
                    <div class="padding-top-default">%</div>
                    <div class="page-subheader">1</div>
                </div>
                <div class="">
                    <div class="">Failed</div>
                    <div class="page-subheader font-big">0</div>
                </div>
            </div>
        </div>
    </body>

</html>

如果值在标记内被硬编码,我想要#附加。输出文件就像。

<html>
    <head>
    </head>
    <body>
        <h1>#Hello#</h1> 
        <div id="something"><span><h1>#Hello Folks!#</h1></span></div>
        <span>#Lovely lady#</span>
        <div id="name">
            <div class="random">
                <div><span>#0#</span></div>
                <div><span>#1#</span></div>
            </div>
        </div>
        <div class="detail ">
            <div class="">#Process#</div>
            <div class="page">#4 of 6#</div>
            <div class=" ">
                <div class="float-left">
                    <div class="padding-top-default">#%#</div>
                    <div class="page-subheader">#1#</div>
                </div>
                <div class="">
                    <div class="">#Failed#</div>
                    <div class="page-subheader font-big">#0#</div>
                </div>
            </div>
        </div>
    </body>

</html>

我已经有了这个java脚本

 <script>
            
          
          //$fakediv = $("<div></div>"); 
        function convertHtml() {
            
 
            $body = $("#demo").text();
             
           $fakediv = $("<div></div>");
            $fakediv.html($body); 
            $fakediv.children().each(function() {
                   if($(this).text())  
                   $(this).text("#" + $(this).text() + "#");
              });
            
            });
          $("#demo").text($fakediv.prop("outerHTML")); //fill in the text are with converted html string 
        
}
            
        //Document is ready to execute the JS    
        $(document).ready(function() {    
            $("#convert").click(function(){
              // alert($("#demo").text());
                convertHtml();
            }); 
        });
        </script>
但输出结果是什么,就像

<div>
    
    
    
        <h1>#Hello#</h1> 
        <div id="something">#Hello Folks!#</div>
        <span>#Lovely lady#</span>
        <div id="name">#
            
                0
                1
            
        #</div>
        <div class="detail ">#
            Process
            4 of 6
            
                
                    %
                    1
                
                
                    Failed
                    0
                
            
        #</div>
    

</div>

6 个答案:

答案 0 :(得分:3)

$(document).ready(function() {
  $('body').find('*').each(function() {
    if ($(this).children().length == 0) {
      $(this).prepend('#').append('#')
    }
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
    <head>
    </head>
    <body>
        <h1>Hello</h1> 
        <div id="something"><span><h1>Hello Folks!</h1></span></div>
        <span>Lovely lady</span>
        <div id="name">
            <div class="random">
                <div><span>0</span></div>
                <div><span>1</span></div>
            </div>
        </div>
        <div class="detail ">
            <div class="">Process</div>
            <div class="page">4 of 6</div>
            <div class=" ">
                <div class="float-left">
                    <div class="padding-top-default">%</div>
                    <div class="page-subheader">1</div>
                </div>
                <div class="">
                    <div class="">Failed</div>
                    <div class="page-subheader font-big">0</div>
                </div>
            </div>
        </div>
    </body>

</html>

答案 1 :(得分:1)

懒惰版(不会对"foo"中的<p>foo <em>bar</em></p>执行任何操作):

&#13;
&#13;
var html = '<html>\n    <head>\n    </head>\n    <body>\n        <h1>Hello</h1> \n        <div id="something"><span><h1>Hello Folks!</h1></span></div>\n        <span>Lovely lady</span>\n        <div id="name">\n            <div class="random">\n                <div><span>0</span></div>\n                <div><span>1</span></div>\n            </div>\n        </div>\n        <div class="detail ">\n            <div class="">Process</div>\n            <div class="page">4 of 6</div>\n            <div class=" ">\n                <div class="float-left">\n                    <div class="padding-top-default">%</div>\n                    <div class="page-subheader">1</div>\n                </div>\n                <div class="">\n                    <div class="">Failed</div>\n                    <div class="page-subheader font-big">0</div>\n                </div>\n            </div>\n        </div>\n    </body>\n\n</html>\n';
    
$html = $("<html/>").html(html);
$html.find('*:not(:has(*))').text(function(_, txt) {
if (txt.trim() == "") return "";
  return "#" + txt + "#";
});
$('#output').text($html[0].outerHTML);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id="output"></pre>
&#13;
&#13;
&#13;

非惰性版本涉及查找文档中的所有文本节点,jQuery不知道该怎么做,因此我们将使用树木漫步者。奖金,没有jQuery:

&#13;
&#13;
var html = '<html>\n    <head>\n    </head>\n    <body>\n        <h1>Hello</h1> \n        <div id="something"><span><h1>Hello Folks!</h1></span></div>\n        <span>Lovely lady</span>\n        <div id="name">\n            <div class="random">\n                <div><span>0</span></div>\n                <div><span>1</span></div>\n            </div>\n        </div>\n        <div class="detail ">\n            <div class="">Process</div>\n            <div class="page">4 of 6</div>\n            <div class=" ">\n                <div class="float-left">\n                    <div class="padding-top-default">%</div>\n                    <div class="page-subheader">1</div>\n                </div>\n                <div class="">\n                    <div class="">Failed</div>\n                    <div class="page-subheader font-big">0</div>\n                </div>\n            </div>\n        </div>\n    </body>\n\n</html>\n';

var impl    = document.implementation;
var htmlDoc = impl.createHTMLDocument("");
htmlDoc.write(html);

var walker = htmlDoc.createTreeWalker(
    htmlDoc.documentElement,
    NodeFilter.SHOW_TEXT, null, false);
var node;
while ((node = walker.nextNode())) {
  if (node.textContent.trim() !== "") {
    node.textContent = "#" + node.textContent + "#";
  }
}

document.getElementById('output').textContent = htmlDoc.documentElement.innerHTML;
&#13;
<pre id="output"></pre>
&#13;
&#13;
&#13;

请注意,由于HTML解析的某些细节,<body>之外的内容可能不一样。并且DBagBaggerWithSwagger对另一个解决方案的注释在这里也是有效的。

答案 2 :(得分:0)

您可以使用text function

$('body *').text(function(_, txt){
   return '#'+txt+'#';
});

这里是demo

如果正文中有任何样式规则和javascripts,那么您可以使用not忽略它们:

$('body *').not('link,style,script').text(function(_, txt){
       return '#'+txt+'#';
});

答案 3 :(得分:0)

为要使用$('.hashed').each(function(index, value){ $(this).text("#" + $(this).text() + "#"); }); 包装文本的所有元素提供一个类。然后使用以下代码:

'*:not(:has(>*))'

如果您不能编辑html,请使用以下css选择最深的元素:

$(document).ready(function(){
  $('*:not(:has(>*))').each(function(index, value){
    $(this).text("#" + $(this).text() + "#");
  });
});

以下是工作代码:

&#13;
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
    <head>
    </head>
    <body>
        <h1>Hello</h1> 
        <div id="something"><span><h1>Hello Folks!</h1></span></div>
        <span>Lovely lady</span>
        <div id="name">
            <div class="random">
                <div><span>0</span></div>
                <div><span>1</span></div>
            </div>
        </div>
        <div class="detail">
            <div>Process</div>
            <div class="page">4 of 6</div>
            <div class=" ">
                <div class="float-left">
                    <div class="padding-top-default">%</div>
                    <div class="page-subheader">1</div>
                </div>
                <div class="">
                    <div>Failed</div>
                    <div class="page-subheader font-big">0</div>
                </div>
            </div>
        </div>
    </body>
</html>
&#13;
    .ty-tabs {
    margin-top: 4px;
    vertical-align: bottom;
    border-bottom: 1px solid #e7e7e7;
    text-align:center;
}

.ty-tabs__list {
    vertical-align: bottom;
}

.ty-tabs__item.active, .ty-tabs .subtab.active {
    background: #fff;
}

.ty-tabs__item, .ty-tabs .subtab {
    display:inline-block;
    vertical-align: bottom;
    white-space: nowrap;
    cursor: pointer;
    border-radius: 0;
    margin: 2px 2px 0 0;
    padding: 0 0 0 3px;
    position: relative;
}
&#13;
&#13;
&#13;

答案 4 :(得分:0)

你走了。与其他人不同,此不会向没有内容的标记添加'##',例如imgbr,空span等等...

function eachNode($root) {
    if ($root.children().size() == 0) {
        if ($root.text().trim() !== '') $root.text('#' + $root.text() + '#');
    } else {
        $root.children().each(function () {
            eachNode($(this));
        });
    }
}

eachNode($(document));

点击这里的小提琴:http://jsfiddle.net/hra0qste/2/

答案 5 :(得分:0)

这也应该有效:

function isHTML(str) {
    var a = document.createElement('div');
    a.innerHTML = str;
    for (var c = a.childNodes, i = c.length; i--; ) {
        if (c[i].nodeType == 1) return true; 
    }
    return false;
}

$( document ).ready(function() {
    var content =   document.getElementsByTagName('*');
    for ( var i = 0; i < content.length; i++ )
    {
        if ( isHTML($(content[i]).html()) == false ) 
        {
            $(content[i]).html('#' + $(content[i]).html() + '#');   
        }          
    }
});