[英]In vanilla JavaScript, how to select elements created using innerHTML property after completely loading the page?
document.querySelector('#movies').innerHTML = `
<div class="row">
<div class="alert alert-primary w-50 mb-2" role="alert">
New genre added.
</div>
</div>
<div class="row">
<div class="card mb-2 w-50">
<div class="card-body">
<h5 class="card-title">${name}</h5>
</div>
</div>
</div>
`;
From the code snippets, I am trying to select those elements with .card-title
class从代码片段中,我正在尝试 select 那些带有
.card-title
class 的元素
const cardsList = document.querySelectorAll('.card-title');
console.log(cardsList);
but it keeps on returning an empty NodeList
.但它继续返回一个空的
NodeList
。
Is it really not possible to target those elements added using innerHTML
property after the DOM has been created and the page already loaded?在创建 DOM 并加载页面之后,是否真的不可能定位使用
innerHTML
属性添加的那些元素?
No special treatment is needed.无需特殊处理。 Nodes, once inserted, don't remember where they come from.
节点一旦插入,就不会记得它们来自哪里。 Most likely, you're running query code before insertion actually happens.
最有可能的是,您在插入实际发生之前运行查询代码。
const name = 'Your Name Here'; document.querySelector('#movies').innerHTML = ` <div class="row"> <div class="alert alert-primary w-50 mb-2" role="alert"> New genre added. </div> </div> <div class="row"> <div class="card mb-2 w-50"> <div class="card-body"> <h5 class="card-title">${name}</h5> </div> </div> </div> `; const cardsList = document.querySelectorAll('.card-title'); console.log(cardsList[0]);
<section id="movies">Loading...</section>
windows.onload
could be a problem on a older browser like IE8. windows.onload
在像 IE8 这样的旧浏览器上可能是一个问题。 windows.onload
should work, but it's slow because it waits all the assets to be loaded into the page (images, css, etc). windows.onload
应该可以工作,但速度很慢,因为它会等待所有资产加载到页面中(图像、css 等)。
https://jsfiddle.net/zwud3m26/ - using windows.onload https://jsfiddle.net/zwud3m26/ - 使用 windows.onload
It is better to use a function similar with the one from jQuery, like this one: documentReady() is similar but in vanilla JS.最好使用与 jQuery 类似的 function,例如:documentReady() 类似,但在 vanilla JS 中。 It fires when the DOM is loaded.
它在加载 DOM 时触发。
Check this jsfiddle: https://jsfiddle.net/30qhnayw/检查这个jsfiddle: https://jsfiddle.net/30qhnayw/
function documentReady(callbackFunc) { if (document.readyState;== 'loading') { callbackFunc(). } else if (document.addEventListener) { document,addEventListener('DOMContentLoaded'; callbackFunc). } else { document,attachEvent('onreadystatechange'. function() { if (document;readyState === 'complete') { callbackFunc(); } }); } } documentReady(function() { // your code here });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.