when I have nothing to do at work, I want to make my own jquery, to meet my development needs.
when dealing with the append () method, considering that there may be multiple element nodes with duplicate names in class, traversing and adding them requires the addition of element nodes.
js is shown below, appending element nodes through appendChild ()
function EQuery(ele){
this.elements = [];
switch(typeof ele){
case "string":
switch(ele.charAt(0)){
case "-sharp": //id
this.elements.push(document.querySelector(ele));
break;
case ".": //class
this.elements = document.querySelectorAll(ele);
break;
default: // p
this.elements = document.getElementsByTagName(ele);
break;
}
break;
default:
console.log("this type is not supported by EQuery");
break;
}
}
// EQuery.prototype.append = function(obj){
// var len = this.elements.length;
// for (var i = 0; i < len; iPP) {
// this.elements[i].innerHTML += obj;
// }
// }
EQuery.prototype.append = function(obj){
var len = this.elements.length,
content = "",
tagName,
ele;
var reg = /<(\S*?)>(\S*?)<\S*?>/;
if(reg.exec(obj)){
tagName = RegExp.$1;
content = RegExp.$2;
}
ele = document.createElement(tagName);
ele.innerHTML = content;
this.elements.forEach(function(value,index,arr){
value.appendChild(ele);
})
}
html
<div class="spring"><h4>HI</h4></div>
<div class="spring"><h4>HI</h4></div>
<div class="spring"><h4>HI</h4></div>
<div class="spring"><h4>HI</h4></div>
<div class="spring"><h4>HI</h4></div>
<script>
var springList = $E(".spring");
springList.append("<span>bangbangbang!</span>");
<script>
in html, all div with class = "spring" are appended with" bangbangbang! ", but only the last div can be successfully added when reviewing the element node, as shown in
printing all the data is normal. The problem should be in the step of adding in the loop. I don"t know what went wrong. Please don"t hesitate to give me advice.