![](/img/trans.png)
[英]The best way to change the innerHTML of a certain type of Elements
[英]Best way to search for elements in innerHTML
我正在使用innerHTML来获取被单击的li元素的内部HTML。 然后,我想在HTML中搜索一些段落标签并找到它们的值,有没有很好的方法呢? 我无法重写列表中的任何HTML,这些HTML是在项目的其他位置生成的,但是我确实知道用于
标签。 jQuery的答案很好。
“搜索” HTML的最佳方法是使用DOM。 请注意,如果您要在其中搜索的容器元素已经存在于DOM中,则无需构造新的虚拟元素,只需检索此父节点并使用相同的方法即可。
var el = document.createElement('div'),
someHtmlToSearch = '<div><p>test content in p</p></div>',
pContent;
el.innerHTML = someHtmlToSearch;
pContent = el.querySelector('p').innerHTML; //search for the first p tag
console.log(pContent); //test content in p
使用jQuery:
// Attach onclick listener to li items of interest
$("your-li-selector").on('click', function () {
// Select all p tags within the clicked element
var pTags = $('p', this);
// Iterate over all p tags
pTags.each(function () {
// Do search actions with `this.innerHtml` or `$(this).html()`
});
});
$("li").click(function(){
var myPrag=this.innerHTML.find("p");
});
然后使用myParag
PS未测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.