标签: nodelist

在 javascript / typescript 中将 Element 转换为 HTMLElement

因此,我使用 querySelectorAll 获取与选择器匹配的元素列表,并将它们存储在 NodeList 中。

然后,我使用 forEach 循环扫描 NodeList,此时每个 individualItem 的类型都是“Element”。

但是,我将这些 individualItems 输入到函数“doThing()”中,该函数期望 individualItem 的类型为“HTMLElement”(我正在使用打字稿)。我想知道是否有一些内置的 js 函数用于将“Element”类型转换为“HTMLElement”类型,或者如果没有,类似的函数可能是什么样子

const h = document.querySelectorAll(someClassString);

h.forEach(individualItem => {
            individualItem.addEventListener(c.EVENT, () => doThing(individualItem));
})    
Run Code Online (Sandbox Code Playgroud)

javascript casting nodelist typescript

7
推荐指数
2
解决办法
1万
查看次数

[] .forEach.call的速度(...?

我非常喜欢在nodeLists上使用forEach方法,如下所示:

var nodes = document.querySelectorAll(".foo");

[].forEach.call(nodes, function (item) {
    //do stuff with item
});
Run Code Online (Sandbox Code Playgroud)

我想知道,这样做的时间是否比常规方式更长?例如

for(var i=0;i<nodes.length;i++){
    //do stuff with nodes[i];
}
Run Code Online (Sandbox Code Playgroud)

javascript foreach call nodelist

6
推荐指数
1
解决办法
4721
查看次数

使用nodeList创建XML文档

我需要使用NodeList创建一个XML Document对象.有人可以帮我做这件事.我已经向您展示了下面的代码和xml

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.*; 
import org.w3c.dom.*;

public class ReadFile {

    public static void main(String[] args) {
        String exp = "/configs/markets";
        String path = "testConfig.xml";
        try {
            Document xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(path);
            XPath xPath = XPathFactory.newInstance().newXPath();
            XPathExpression xPathExpression = xPath.compile(exp);
            NodeList nodes = (NodeList)
              xPathExpression.evaluate(xmlDocument,
                                       XPathConstants.NODESET);

        } catch (Exception ex) {
            ex.printStackTrace();
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)

xml文件如下所示

<configs>
    <markets>   
        <market>
            <name>Real</name>
        </market>
        <market>
            <name>play</name>
        </market>
    </markets>
</configs>
Run Code Online (Sandbox Code Playgroud)

提前致谢..

java xml dom backend nodelist

6
推荐指数
1
解决办法
4万
查看次数

为什么JavaScript的getElementsByClassName提供的对象不是数组?

我正在尝试使用特定类名在页面上的所有元素的JavaScript(不使用jQuery)中获取列表.因此,我使用getElementsByClassName()函数,如下所示:

var expand_buttons = document.getElementsByClassName('expand');
console.log(expand_buttons, expand_buttons.length, expand_buttons[0]);
Run Code Online (Sandbox Code Playgroud)

请注意,我的页面上有三个锚元素,类为"expand".这个console.log()输出

[] 0 undefined
Run Code Online (Sandbox Code Playgroud)

接下来,对于踢,我将expand_buttons扔到它自己的数组中,如下所示:

var newArray = new Array(expand_buttons);
console.log(newArray, newArray.length);
Run Code Online (Sandbox Code Playgroud)

这突然输出

[NodeList[3]] 1
Run Code Online (Sandbox Code Playgroud)

我可以点击节点列表,查看页面上三个"展开"锚元素的属性.值得注意的是,我能够在w3schools测试页面中使用我的代码.

还可能需要注意的是,我对document.getElementsByName的使用实际上输出(到控制台)一个元素数组,但是当我要求它的长度时,它告诉我0.同样,如果我尝试使用它来访问数组元素array_name[0]正常情况下,它输出'undefined',尽管当我将对象打印到控制台时,数组内部明显存在元素.

有没有人知道为什么会这样?我只想循环遍历DOM元素,而我现在正在避免使用jQuery,因为我正在尝试使用vanilla JavaScript进行编码.

谢谢,

ParagonRG

javascript arrays nodelist chromium

6
推荐指数
1
解决办法
1490
查看次数

使用forEach方法迭代NodeList

我想使用forEach方法迭代NodeList,我搜索了该方法,我发现解决方法是将NodeList转换为数组:

var nodesArray = Array.prototype.slice.call(nodeList);
nodesArray.forEach(function(node) { 
    //...
})
Run Code Online (Sandbox Code Playgroud)

但我不明白为什么我们使用这种Array.prototype.slice方法?

javascript foreach nodelist slice htmlcollection

6
推荐指数
1
解决办法
2656
查看次数

使用Java中的XPath解析XML - 使用Java中的Xpath和NodeList从XML文件中获取数据

我有这个xml文件,我想用Xpath获取一些值.

工作的一半已经完成但我在文件的最后部分遇到了一些麻烦(States Node)

<?xml version="1.0" encoding="UTF-8"?>
<favoris>
    <workflow codewf="wf1000">
        <information>
            <title>wf1</title>
            <desc>description 1</desc>
            <nberState>2</nberState>
            <text>text text text text text text text</text>
        </information>
        <states>
            <state id="1" IDemployee="2">description1</state>
            <state id="2" IDemployee="3">description2</state>
        </states>
    </workflow>

    <workflow codewf="wf2000">
        <information>
            <title>wf2</title>
            <desc>description 2</desc>
            <nberState>3</nberState>
            <text>text text text text text text text</text>
        </information>
        <states>
            <state id="1" IDemployee="3">description1</state>
            <state id="2" IDemployee="2">description2</state>
            <state id="3" IDemployee="4">description2</state>
        </states>
    </workflow>

</favoris>
Run Code Online (Sandbox Code Playgroud)

这里是java代码:package myxml;

import java.io.FileReader;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class xmlParty {
  public …
Run Code Online (Sandbox Code Playgroud)

java xml xpath nodelist

5
推荐指数
1
解决办法
2万
查看次数

XPath NodeList顺序(Java)

我有以下XML结构。

<?xml version="1.0" encoding="UTF-8"?>
<root> 
  <header> 
    <row> 
      <column n="name" />
      <column n="age" />
      <column n="email" />
    </row> 
  </header>  
  <body> 
    <row> 
      <column>Foo</column>  
      <column>99</column>  
      <column>foo@test.com</column> 
    </row>  
  </body> 
</root>
Run Code Online (Sandbox Code Playgroud)

我正在使用以下XPath表达式获取标题列,同样也获取正文列。

PathExpression headerExpr = xPath.compile("/root/header/row/column/@n");
NodeList headerColumns = (NodeList) headerExpr.evaluate(document, XPathConstants.NODESET);
PathExpression bodyExpr = xPath.compile("/root/body/row/column");
NodeList bodyColumns = (NodeList) bodyExpr.evaluate(document, XPathConstants.NODESET);
for (int i = 0; i < headerColumns.getLength(); i++) {
                System.out.println((Attr) headerColumns .item(i)).getValue() + ": " + bodyColumns.item(i).getTextContent());
        }
Run Code Online (Sandbox Code Playgroud)

我是否可以假设XPath将始终以相同的顺序返回标头和正文列,以便它们始终匹配?或者甚至可以假设这些列始终按文档顺序返回?

java xpath nodelist

5
推荐指数
1
解决办法
2558
查看次数

如何打乱 NodeList

假设我有一个节点列表:

list = document.querySelectorAll('div');

我想把它洗牌。我该怎么做?

我遇到的唯一答案是,这里建议将节点列表变成array使用

var arr = [].concat(x);

同样,MDN建议如下(将 NodeList 转换为array):

var turnObjToArray = function(obj) {
  return [].map.call(obj, function(element) {
    return element;
  })
};
Run Code Online (Sandbox Code Playgroud)

我的问题是,如果不将 NodeList 转换为数组,是否就没有办法做到这一点?

并且,以上两种方法哪种更好呢?

而且,一旦将 NodeList 转换为数组,当您对数组的某些成员进行操作时,会发生什么变化吗?(即从数组中删除一个节点是否会将其从 NodeList 中删除)?

javascript arrays nodelist

5
推荐指数
1
解决办法
2904
查看次数

实现List <Node>

我决定实现摘要List<Node>.这是它的一部分:

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

    public class myNodeList implements NodeList{


    Node root = null;
    int length = 0;

    public myNodeList() {}   
    public void addNode(Node node) {  
        if(root == null)   
        {
            root = node;  
               }
          else          
         root.appendChild(node);   
        length++;   
        System.out.println("this is the added node " +node);
    }      
     } 
Run Code Online (Sandbox Code Playgroud)

但是当我尝试add一个节点时,它给了我以下异常:

Exception in thread "main" org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted. 
at com.sun.org.apache.xerces.internal.dom.NodeImpl.insertBefore(NodeImpl.java:478)
at com.sun.org.apache.xerces.internal.dom.NodeImpl.appendChild(NodeImpl.java:235)
at pageparsertest.myNodeList.addNode(myNodeList.java:27)
Run Code Online (Sandbox Code Playgroud)

这是因为Node root = …

java dom list nodelist

5
推荐指数
1
解决办法
431
查看次数

遍历 NodeList

我正在寻找一种面向未来的方法来迭代 NodeList (即来自element.querySelectorAll(selector))以及跨浏览器兼容。之前我一直在使用 ES6 Spread 功能,但是 IE 不支持 spread,所以我使用了 shim。我觉得这有点矫枉过正而且效率低下。然后我遇到了 hack Array.prototype.forEach.call。它有效,但对我来说看起来很臭。

迭代 NodeList 的最佳方法是什么?

我偏向于向后兼容性和干净的代码,但如果您的答案也适用于下面的任何其他标准,我们将不胜感激。

  1. 可读性
  2. 面向未来
  3. 速度

我研究了JavaScript 通过 NodeList 进行迭代,其中介绍了一些方法。不过,不用担心可读性、兼容性等问题,只要能用就行。

我遇到的一些方法是:

const elems = document.querySelectorAll('img');

[].forEach.call(elems, function (o) { console.log(o) });

[...elems].foreach(function (o) { console.log(o) });

for (var i = 0; i < elems.length; i++) {
    console.log(elems[i]);
}

for (var i = elems.length - 1; i >= 0; i--) {
    console.log(elems[i]);
}

// User-defined
var forEach = function (array, callback, scope) { …
Run Code Online (Sandbox Code Playgroud)

javascript cross-browser nodelist

5
推荐指数
1
解决办法
3146
查看次数