有没有办法通过id(和/或类)从使用jQuery parseHTML函数创建的DOM元素数组中获取特定的DOM元素?
我不是在寻找document.getElementByID(),因为它从当前页面获取元素。
背景
我必须从具有动态内容的网页创建pdf。为了保持pdf看起来一致,我创建了一个包含特定ID的固定大小元素的html模板。
我想编写一个java脚本代码:
1 - 加载模板页面的内容
2 - 从当前页面(具有特定ID)和
中获取特定的s3 - 将这些特定的s插入模板的目标区域。
我这样做的方式是:
使用AJAX异步函数读取模板文件并将其存储到名为templ的变量中。
然后按照这样的模式:
var template = $.parseHTML(templ); //gives an array of DOM elements
//loop through all the children and children of children of template and when I found a match:
{
var a = $('#id_of_div_in_source_page'); //
template[i].children[j].children[k].children[l].innerHTML = a.html();
}
最后将'模板'导出为html。
我正在寻找跳过整个循环过程的方法。
P.S。与this question有点不同,因为我必须为多个元素做这件事。
答案 0 :(得分:0)
我的解决方案基于@ adneo的评论。我循环遍历所有元素并调用outerHTML并将其连接成一个字符串:
var outputHTML = "";
for(var j = 0; j < template.length; j++)
{
var temp = $(template).get(j).outerHTML; //temp is undefined for empty nodes!
if(temp !== undefined)
{
outputHTML += temp;
}
}
感谢Adeneo。