$(selector,element)Native JS替代品($(selector, element) Native JS alternative)

您好我试图从我的平台一次删除所有jQuery一行。

但是我在找到替代品时遇到了一些麻烦

$('[data-attribute="value"]', GenericHTMLElement);

我希望这会是简单的

var div = document.createElement('div');
div.innerHTML = '<div><span data-attribute="value"></span><span data-something-else="1000"></span></div>';
var b = div.childNodes;

var a = b.querySelector('[data-attribute="value"]'); 
  
 

但是这也行不通。 对我有什么建议吗?

Hi I'm trying to remove all jQuery from my platform one line at a time.

But I'm having some trouble finding a replacement for this

$('[data-attribute="value"]', GenericHTMLElement);

I was hoping it would be something simple like

var div = document.createElement('div');
div.innerHTML = '<div><span data-attribute="value"></span><span data-something-else="1000"></span></div>';
var b = div.childNodes;

var a = b.querySelector('[data-attribute="value"]'); 
  
 

But that's not working either. Does have any suggestions for me?

最满意答案

评论说,

childNodes会给你一个元素列表。 该列表将不具有querySelector。 如果你在节点上循环,你应该能够得到它。 但是,我的建议只是做div.querySelector(...)

具体来说,它将是NodeList类型。 这是一个节点的集合。 所以你不能在其上运行querySelector 。 您可以循环遍历所有节点并对它们执行querySelector ,也可以对父div执行此操作。

var div = document.createElement('div');
div.innerHTML = '<div><span data-attribute="value">Dummy Text</span><span data-something-else="1000"></span></div>';
var b = div.childNodes;

console.log('Type of childNodes is: ', Object.prototype.toString.call(b))

// getting element using loop over childNodes
for(var i = 0; i<b.length; i++) {
  var el = b[i].querySelector('[data-attribute="value"]');
  el && console.log(el.textContent)
}

// getting element using parent elenent.
var el1 = div.querySelector('[data-attribute="value"]');
console.log(el1.textContent) 
  
 

As commented,

childNodes will give you a list of elements. This list will not have querySelector. If you loop over nodes, you should be able to get it though. But, my suggestion is just do div.querySelector(...)

To be specific, it will be of type NodeList. This is a collection of nodes. So you cannot run querySelector on it. You can either loop over all nodes and do querySelector on them or just so this operation on parent div.

var div = document.createElement('div');
div.innerHTML = '<div><span data-attribute="value">Dummy Text</span><span data-something-else="1000"></span></div>';
var b = div.childNodes;

console.log('Type of childNodes is: ', Object.prototype.toString.call(b))

// getting element using loop over childNodes
for(var i = 0; i<b.length; i++) {
  var el = b[i].querySelector('[data-attribute="value"]');
  el && console.log(el.textContent)
}

// getting element using parent elenent.
var el1 = div.querySelector('[data-attribute="value"]');
console.log(el1.textContent) 
  
 

更多推荐