我正在构建一个辅助函数,以将元素插入DOM。这是我到目前为止的内容:
function insertElem(numberOfElems, elemTag, elemId, elemClass, parentSelector){
/*
* numberOfElements:- Pass in a plain whole integer.
* elemId:- Pass in a name for the element id (inside "" or ''),
an integer is appended to the id name by the for loop.
* elemTag:- Pass in the element tag type (inside "" or '').
* parentSelector:- Pass in the identifier of the parent element (inside "" or '')
*querySelector prefixes: # = id
. = class
none = tag
*/
if (numberOfElems > 1) {
for (i = 0; i < numberOfElems; i++) {
var elem = this[elemId + i];
elem = document.createElement(elemTag);
elem.id = elemId + '_' + i;
elem.className = elemClass;
parentEl = document.querySelector(parentSelector);
parentEl.appendChild(elem);
}
} else {
var elem = this[elemId];
elem = document.createElement(elemTag);
elem.id = elemId;
elem.className = elemClass;
parentEl = document.querySelector(parentSelector);
parentEl.appendChild(elem);
}
}
我希望能够检查“ elem”是否为HTML媒体元素,以便可以向函数添加参数(“ elemSrc”)。
伪代码:
if (elem is an html media element) {
elem.src = media url;
}
答案 0 :(得分:3)
您可以只使用instanceof来查看它是否是HTMLMediaElement
console.log(document.getElementById('test1') instanceof HTMLMediaElement)
console.log(document.getElementById('test2') instanceof HTMLMediaElement)
<video id="test1"></video>
<div id="test2"></video>
答案 1 :(得分:0)
紧接着Dave的回答,HTMLMediaElement
是HTMLAudioElement
和HTMLVideoElement
的基类,因此,如果要检查特定类型的媒体,也可以使用instanceof
分别提到的类型。
答案 2 :(得分:0)
感谢小贴士Dave,这就是我现在想要的:-
function insertElem(numberOfElems, elemTag, elemId, elemClass, parentSelector, elemSrc){
/*
* numberOfElements:- Pass in a whole integer.
* elemTag:- Pass in the element tag type (inside "" or '').
* elemId:- Pass in a name for the element id (inside "" or ''),
an integer is appended to the id name by the for loop.
* elemClass:- Pass in a name for element class (inside "" or '').
* parentSelector:- Pass in the identifier of the parent element (inside "" or '')
* querySelector prefixes: # = id
. = class
none = tag
*elemSrc:- Pass in the source media url (inside "" or '').
*/
if (numberOfElems > 1) {
for (i = 0; i < numberOfElems; i++) {
var elem = this[elemId + i];
elem = document.createElement(elemTag);
elem.id = elemId + '_' + i;
if (elemClass) {
elem.className = elemClass;
}
parentEl = document.querySelector(parentSelector);
parentEl.appendChild(elem);
if(elem instanceof HTMLMediaElement) {
elem.src = elemSrc;
}
}
} else {
var elem = this[elemId];
elem = document.createElement(elemTag);
elem.id = elemId;
if (elemClass) {
elem.className = elemClass;
}
parentEl = document.querySelector(parentSelector);
parentEl.appendChild(elem);
if(elem instanceof HTMLMediaElement) {
elem.src = elemSrc;
}
}
}