如何使用JavaScript获取HTML中的子元素?
程序:
$(function(){
var child = document.getElementById("row");
var i;
$("#subpage").html(child.childNodes.length);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<table>
<tr id="row">
<td> This is td </td>
<td> This is td2 </td>
</tr>
</table>
<div id="subpage"> </div>
&#13;
我希望上面的程序会将输出打印为&#34; 2&#34;。但它给出了&#34; 5&#34;。包含id为&#34; row&#34;的元素有2个元素 TD。但它给出了&#34; 5&#34;。那么&#34; 5&#34;打印?
输出:
This is td This is td2
5
答案 0 :(得分:3)
您已获得5,因为该行中有两个elements和三个text nodes,$(function(){
console.log("nodeType 1 is Element, 3 is Text");
var child = document.getElementById("row");
var i;
for (i = 0; i < child.childNodes.length; ++i) {
console.log(i + ": nodeType = " + child.childNodes[i].nodeType);
}
});
正好是这样的:子节点。有多种节点(主要是:元素,文本节点和注释节点)。以下是该结构中的节点:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<table>
<tr id="row">
<td> This is td </td>
<td> This is td2 </td>
</tr>
</table>
<div id="subpage"> </div>
&#13;
$(function(){
console.log("nodeType 1 is Element, 3 is Text");
var child = document.getElementById("row");
var i;
for (i = 0; i < child.children.length; ++i) {
console.log(i + ": nodeType = " + child.children[i].nodeType);
}
});
&#13;
如果您只想要子元素,请使用DOM children
property(适用于所有现代浏览器,但不适用于非旧版浏览器):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<table>
<tr id="row">
<td> This is td </td>
<td> This is td2 </td>
</tr>
</table>
<div id="subpage"> </div>
&#13;
$(function(){
console.log("nodeType 1 is Element, 3 is Text");
var child = document.getElementById("row");
var i;
$(child).children().each(function(i) {
console.log(i + ": nodeType = " + this.nodeType);
});
});
&#13;
...或jQuery&#39; children
method:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<table>
<tr id="row">
<td> This is td </td>
<td> This is td2 </td>
</tr>
</table>
<div id="subpage"> </div>
&#13;
margin: 10px 5px 2px 8px;
&#13;
答案 1 :(得分:2)
为什么不检查child.childNodes
内的内容?
根据文件
元素内的空格被视为文本,文本被视为文本 被视为节点。注释也被视为节点。
这就是为什么你得到5而不是2,因为有3个额外的文本节点,你没有预料到。请改用child.children
。
$(function(){
var row = document.querySelector('#row');
var row_no_ws = document.querySelector('#row_no_ws');
var subpage = document.querySelector('#subpage');
subpage.innerHTML = 'Row childNodes: ' + row.childNodes.length + '<br>' +
'Row using children: ' + row.children.length + '<br>' +
'Row childNodes no whitespaces: ' + row_no_ws.childNodes.length
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<table>
<tr id="row">
<td> This is td </td>
<td> This is td2 </td>
</tr>
</table>
<table>
<tr id="row_no_ws"><td> This is td </td><td> This is td2 </td></tr>
</table>
<div id="subpage"> </div>
&#13;
答案 2 :(得分:1)
如果您执行控制台日志console.log(child.childNodes)
它还包括元素之前的空格,以及.childNodes之间的空格也将这些空格计为子级。如果您使用child.childrens.length
,它将忽略空格并将计数计为2。
答案 3 :(得分:1)
您可以简单地使用jQuery # An example of embedding CEF browser in a PyQt4 application.
# Tested with PyQt 4.10.3 (Qt 4.8.5).
import os, sys
libcef_dll = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'libcef.dll')
if os.path.exists(libcef_dll):
# Import a local module
if (2,7) <= sys.version_info < (2,8):
import cefpython_py27 as cefpython
elif (3,4) <= sys.version_info < (3,4):
import cefpython_py34 as cefpython
else:
raise Exception("Unsupported python version: %s" % sys.version)
else:
# Import an installed package
from cefpython3 import cefpython
from PyQt4 import QtGui
from PyQt4 import QtCore
def GetApplicationPath(file=None):
import re, os, platform
# On Windows after downloading file and calling Browser.GoForward(),
# current working directory is set to %UserProfile%.
# Calling os.path.dirname(os.path.realpath(__file__))
# returns for eg. "C:\Users\user\Downloads". A solution
# is to cache path on first call.
if not hasattr(GetApplicationPath, "dir"):
if hasattr(sys, "frozen"):
dir = os.path.dirname(sys.executable)
elif "__file__" in globals():
dir = os.path.dirname(os.path.realpath(__file__))
else:
dir = os.getcwd()
GetApplicationPath.dir = dir
# If file is None return current directory without trailing slash.
if file is None:
file = ""
# Only when relative path.
if not file.startswith("/") and not file.startswith("\\") and (
not re.search(r"^[\w-]+:", file)):
path = GetApplicationPath.dir + os.sep + file
if platform.system() == "Windows":
path = re.sub(r"[/\\]+", re.escape(os.sep), path)
path = re.sub(r"[/\\]+$", "", path)
return path
return str(file)
def ExceptHook(excType, excValue, traceObject):
import traceback, os, time, codecs
# This hook does the following: in case of exception write it to
# the "error.log" file, display it to the console, shutdown CEF
# and exit application immediately by ignoring "finally" (os._exit()).
errorMsg = "\n".join(traceback.format_exception(excType, excValue,
traceObject))
errorFile = GetApplicationPath("error.log")
try:
appEncoding = cefpython.g_applicationSettings["string_encoding"]
except:
appEncoding = "utf-8"
if type(errorMsg) == bytes:
errorMsg = errorMsg.decode(encoding=appEncoding, errors="replace")
try:
with codecs.open(errorFile, mode="a", encoding=appEncoding) as fp:
fp.write("\n[%s] %s\n" % (
time.strftime("%Y-%m-%d %H:%M:%S"), errorMsg))
except:
print("[pyqt.py] WARNING: failed writing to error file: %s" % (
errorFile))
# Convert error message to ascii before printing, otherwise
# you may get error like this:
# | UnicodeEncodeError: 'charmap' codec can't encode characters
errorMsg = errorMsg.encode("ascii", errors="replace")
errorMsg = errorMsg.decode("ascii", errors="replace")
print("\n"+errorMsg+"\n")
cefpython.QuitMessageLoop()
cefpython.Shutdown()
os._exit(1)
class MainWindow(QtGui.QMainWindow):
mainFrame = None
def __init__(self):
super(MainWindow, self).__init__(None)
#self.createMenu()
self.mainFrame = MainFrame(self)
self.setCentralWidget(self.mainFrame)
self.resize(1024, 768)
self.setWindowTitle('PyQT CEF 3 example')
self.setFocusPolicy(QtCore.Qt.StrongFocus)
def createMenu(self):
menubar = self.menuBar()
filemenu = menubar.addMenu("&File")
filemenu.addAction(QtGui.QAction("Open", self))
filemenu.addAction(QtGui.QAction("Exit", self))
aboutmenu = menubar.addMenu("&About")
def focusInEvent(self, event):
cefpython.WindowUtils.OnSetFocus(int(self.centralWidget().winId()), 0, 0, 0)
def closeEvent(self, event):
self.mainFrame.chrom.browser.CloseBrowser()
class MainFrame(QtGui.QWidget):
browser = None
def __init__(self, parent=None):
super(MainFrame, self).__init__(parent)
self.chrom = chrom()
self.initUi()
#windowInfo = cefpython.WindowInfo()
#windowInfo.SetAsChild(int(self.winId()))
#self.browser = cefpython.CreateBrowserSync(windowInfo,
#browserSettings={},
#navigateUrl="http://stackoverflow.com/")
#self.show()
def initUi(self):
self.button = QtGui.QPushButton()
mainlayout = QtGui.QVBoxLayout()
mainlayout.addWidget(self.button)
mainlayout.addWidget(self.chrom)
self.setLayout(mainlayout)
#def moveEvent(self, event):
#cefpython.WindowUtils.OnSize(int(self.winId()), 0, 0, 0)
#def resizeEvent(self, event):
#cefpython.WindowUtils.OnSize(int(self.winId()), 0, 0, 0)
class chrom(QtGui.QWidget):
def __init__(self, parent=None):
super(chrom, self).__init__(parent)
windowInfo = cefpython.WindowInfo()
windowInfo.SetAsChild(int(self.winId()))
self.browser = cefpython.CreateBrowserSync(windowInfo,
browserSettings={},
navigateUrl="https://www.baidu.com")
def moveEvent(self, event):
cefpython.WindowUtils.OnSize(int(self.winId()), 0, 0, 0)
def resizeEvent(self, event):
cefpython.WindowUtils.OnSize(int(self.winId()), 0, 0, 0)
class CefApplication(QtGui.QApplication):
timer = None
def __init__(self, args):
super(CefApplication, self).__init__(args)
self.createTimer()
def createTimer(self):
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.onTimer)
self.timer.start(10)
def onTimer(self):
# The proper way of doing message loop should be:
# 1. In createTimer() call self.timer.start(0)
# 2. In onTimer() call MessageLoopWork() only when
# QtGui.QApplication.instance()->hasPendingEvents() returns False.
# But... there is a bug in Qt, hasPendingEvents() returns always true.
cefpython.MessageLoopWork()
def stopTimer(self):
# Stop the timer after Qt message loop ended, calls to MessageLoopWork()
# should not happen anymore.
self.timer.stop()
if __name__ == '__main__':
print("[pyqt.py] PyQt version: %s" % QtCore.PYQT_VERSION_STR)
print("[pyqt.py] QtCore version: %s" % QtCore.qVersion())
# Intercept python exceptions. Exit app immediately when exception
# happens on any of the threads.
sys.excepthook = ExceptHook
# Application settings
settings = {
# "cache_path": "webcache/", # Disk cache
"debug": True, # cefpython debug messages in console and in log_file
"log_severity": cefpython.LOGSEVERITY_INFO, # LOGSEVERITY_VERBOSE
"log_file": GetApplicationPath("debug.log"), # Set to "" to disable.
# This directories must be set on Linux
"locales_dir_path": cefpython.GetModuleDirectory()+"/locales",
"resources_dir_path": cefpython.GetModuleDirectory(),
"browser_subprocess_path": "%s/%s" % (
cefpython.GetModuleDirectory(), "subprocess")
}
# Command line switches set programmatically
switches = {
# "proxy-server": "socks5://127.0.0.1:8888",
# "enable-media-stream": "",
# "--invalid-switch": "" -> Invalid switch name
}
cefpython.Initialize(settings, switches)
app = CefApplication(sys.argv)
mainWindow = MainWindow()
mainWindow.show()
app.exec_()
app.stopTimer()
# Need to destroy QApplication(), otherwise Shutdown() fails.
# Unset main window also just to be safe.
del mainWindow
del app
cefpython.Shutdown()
。
children()
&#13;
$(function(){
$("#subpage").html($("#row").children().length);
/* you could also use
$("#subpage").html($("#row").children("td").length);
*/
});
&#13;
答案 4 :(得分:0)
参考w3schools - HTML DOM childNodes Property
注意:元素内的空格被视为文本,文本是 被视为节点。注释也被视为节点。
那里,
<tr id ="row">
newline
<td>
newline
<td>
newline
</tr>
So, it has 5 child Nodes.
在您的情况下,如果html构造是
<tr id="row"><td></td><td></td></tr>,
这将是2
答案 5 :(得分:0)
you can just do $("#row td")
with jQuery to get td
's nested within #row
$(function(){
var child = $("#row td");
$("#subpage").html(child.length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<table>
<tr id="row">
<td> This is td </td>
<td> This is td2 </td>
</tr>
</table>
<div id="subpage"> </div>
答案 6 :(得分:-2)
$("#subpage").html($('#row td').length);
答案 7 :(得分:-2)
试试这个:
var c = document.getElementById("subpage").children.length;