Val*_*Val 88 javascript jquery
<div class="title">
I am text node
<a class="edit">Edit</a>
</div>
Run Code Online (Sandbox Code Playgroud)
我希望得到"我是文本节点",不希望删除"编辑"标签,并且需要跨浏览器解决方案.
Jam*_*ice 73
var text = $(".title").contents().filter(function() {
return this.nodeType == Node.TEXT_NODE;
}).text();
Run Code Online (Sandbox Code Playgroud)
这将获取contents所选元素,并对其应用过滤函数.filter函数仅返回文本节点(即那些节点nodeType == Node.TEXT_NODE).
Dog*_*ert 52
您可以使用第一个childNode获取nodeValue
$('.title')[0].childNodes[0].nodeValue
Run Code Online (Sandbox Code Playgroud)
Sha*_*ard 12
如果您的意思是获取元素中第一个文本节点的值,则此代码将起作用:
var oDiv = document.getElementById("MyDiv");
var firstText = "";
for (var i = 0; i < oDiv.childNodes.length; i++) {
var curNode = oDiv.childNodes[i];
if (curNode.nodeName === "#text") {
firstText = curNode.nodeValue;
break;
}
}
Run Code Online (Sandbox Code Playgroud)
你可以在这里看到这个:http://jsfiddle.net/ZkjZJ/
Yuv*_* A. 11
另一个可用于"复杂"或深度嵌套元素的本机JS解决方案是使用NodeIterator.将NodeFilter.SHOW_TEXT作为第二个参数("whatToShow"),并遍历刚刚元素的文本节点孩子.
var root = document.getElementById('...'),
iter = document.createNodeIterator (root, NodeFilter.SHOW_TEXT),
textnode;
while (textnode = iter.nextNode()) {
// do something with the text node
}
Run Code Online (Sandbox Code Playgroud)
你也可以使用TreeWalker.两者之间的区别在于它NodeIterator是一个简单的线性迭代器,同时TreeWalker允许您通过兄弟和祖先进行导航.
首先,在DOM中查找文本时请始终牢记这一点。
该问题将使您注意XML / HTML的结构。
在这个纯JavaScript示例中,我考虑了多个文本节点可能与其他类型的节点交错的可能性。但是,最初,我没有通过空格判断,而是将过滤任务留给了其他代码。
在此版本中,我NodeList从调用/客户端代码传递进来。
/**
* Gets strings from text nodes. Minimalist. Non-robust. Pre-test loop version.
* Generic, cross platform solution. No string filtering or conditioning.
*
* @author Anthony Rutledge
* @param nodeList The child nodes of a Node, as in node.childNodes.
* @param target A positive whole number >= 1
* @return String The text you targeted.
*/
function getText(nodeList, target)
{
var trueTarget = target - 1,
length = nodeList.length; // Because you may have many child nodes.
for (var i = 0; i < length; i++) {
if ((nodeList[i].nodeType === Node.TEXT_NODE) && (i === trueTarget)) {
return nodeList[i].nodeValue; // Done! No need to keep going.
}
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
当然,通过node.hasChildNodes()先进行测试,就无需使用预测试循环。
/**
* Gets strings from text nodes. Minimalist. Non-robust. Post-test loop version.
* Generic, cross platform solution. No string filtering or conditioning.
*
* @author Anthony Rutledge
* @param nodeList The child nodes of a Node, as in node.childNodes.
* @param target A positive whole number >= 1
* @return String The text you targeted.
*/
function getText(nodeList, target)
{
var trueTarget = target - 1,
length = nodeList.length,
i = 0;
do {
if ((nodeList[i].nodeType === Node.TEXT_NODE) && (i === trueTarget)) {
return nodeList[i].nodeValue; // Done! No need to keep going.
}
i++;
} while (i < length);
return null;
}
Run Code Online (Sandbox Code Playgroud)
在此,该函数getTextById()使用了两个辅助函数:getStringsFromChildren()和filterWhitespaceLines()。
getStringsFromChildren()
/**
* Collects strings from child text nodes.
* Generic, cross platform solution. No string filtering or conditioning.
*
* @author Anthony Rutledge
* @version 6.0
* @param parentNode An instance of the Node interface, such as an Element. object.
* @return Array of strings, or null.
* @throws TypeError if the parentNode is not a Node object.
*/
function getStringsFromChildren(parentNode)
{
var strings = [],
nodeList,
length;
if (!parentNode instanceof Node) {
throw new TypeError("The parentNode parameter expects an instance of a Node.");
}
if (!parentNode.hasChildNodes()) {
return null; // We are done. Node may resemble <element></element>
}
nodeList = parentNode.childNodes;
length = nodeList.length;
for (var i = 0; i < length; i++) {
if (nodeList[i].nodeType === Node.TEXT_NODE) {
strings.push(nodeList[i].nodeValue);
}
}
if (strings.length > 0) {
return strings;
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
filterWhitespaceLines()
/**
* Filters an array of strings to remove whitespace lines.
* Generic, cross platform solution.
*
* @author Anthony Rutledge
* @version 6.0
* @param textArray a String associated with the id attribute of an Element.
* @return Array of strings that are not lines of whitespace, or null.
* @throws TypeError if the textArray param is not of type Array.
*/
function filterWhitespaceLines(textArray)
{
var filteredArray = [],
whitespaceLine = /(?:^\s+$)/; // Non-capturing Regular Expression.
if (!textArray instanceof Array) {
throw new TypeError("The textArray parameter expects an instance of a Array.");
}
for (var i = 0; i < textArray.length; i++) {
if (!whitespaceLine.test(textArray[i])) { // If it is not a line of whitespace.
filteredArray.push(textArray[i].trim()); // Trimming here is fine.
}
}
if (filteredArray.length > 0) {
return filteredArray ; // Leave selecting and joining strings for a specific implementation.
}
return null; // No text to return.
}
Run Code Online (Sandbox Code Playgroud)
getTextById()
/**
* Gets strings from text nodes. Robust.
* Generic, cross platform solution.
*
* @author Anthony Rutledge
* @version 6.0
* @param id A String associated with the id property of an Element.
* @return Array of strings, or null.
* @throws TypeError if the id param is not of type String.
* @throws TypeError if the id param cannot be used to find a node by id.
*/
function getTextById(id)
{
var textArray = null; // The hopeful output.
var idDatatype = typeof id; // Only used in an TypeError message.
var node; // The parent node being examined.
try {
if (idDatatype !== "string") {
throw new TypeError("The id argument must be of type String! Got " + idDatatype);
}
node = document.getElementById(id);
if (node === null) {
throw new TypeError("No element found with the id: " + id);
}
textArray = getStringsFromChildren(node);
if (textArray === null) {
return null; // No text nodes found. Example: <element></element>
}
textArray = filterWhitespaceLines(textArray);
if (textArray.length > 0) {
return textArray; // Leave selecting and joining strings for a specific implementation.
}
} catch (e) {
console.log(e.message);
}
return null; // No text to return.
}
Run Code Online (Sandbox Code Playgroud)
接下来,将返回值(数组或null)发送到应在其中处理的客户端代码。希望该数组应具有真实文本的字符串元素,而不是空白行。
未返回空字符串(""),因为您需要一个文本节点来正确指示有效文本的存在。返回()可能会给人一种错误的印象,即存在一个文本节点,从而使某人假设他们可以通过更改的值来更改文本。这是错误的,因为在空字符串的情况下文本节点不存在。"".nodeValue
范例1:
<p id="bio"></p> <!-- There is no text node here. Return null. -->
Run Code Online (Sandbox Code Playgroud)
范例2:
<p id="bio">
</p> <!-- There are at least two text nodes ("\n"), here. -->
Run Code Online (Sandbox Code Playgroud)
当您想通过隔开HTML使其易于阅读时,就会出现问题。现在,即使没有人类可读有效的文本,还有新行文本节点("\n"字符)在他们的.nodeValue属性。
人类将示例一和示例二视为功能上等同的-空元素等待填充。DOM与人类推理不同。这就是为什么getStringsFromChildren()函数必须确定文本节点是否存在并将这些.nodeValue值收集到数组中的原因。
for (var i = 0; i < length; i++) {
if (nodeList[i].nodeType === Node.TEXT_NODE) {
textNodes.push(nodeList[i].nodeValue);
}
}
Run Code Online (Sandbox Code Playgroud)
在例如两个,两个文本节点确实存在,getStringFromChildren()将返回.nodeValue他们两个("\n")。但是,filterWhitespaceLines()使用正则表达式过滤掉纯空格字符的行。
返回null而不是换行("\n")字符是对客户/调用代码说谎的一种形式吗?用人类的话说,没有。用DOM来讲,是的。但是,这里的问题是获取文本,而不是对其进行编辑。没有人工文本可以返回到调用代码。
人们永远无法知道某人的HTML中可能出现多少个换行符。创建寻找“第二”换行符的计数器是不可靠的。它可能不存在。
当然,更进一步,在带有多余空格的空元素中编辑文本的问题<p></p>(示例2)可能意味着销毁(也许跳过)段落标记之间的所有文本节点,以确保该元素正好包含其内容应该显示。
无论如何,除了您要进行一些非凡的事情之外,您都需要一种方法来确定哪个文本节点的.nodeValue属性具有您要编辑的真实的,可读的文本。filterWhitespaceLines让我们到达一半。
var whitespaceLine = /(?:^\s+$)/; // Non-capturing Regular Expression.
for (var i = 0; i < filteredTextArray.length; i++) {
if (!whitespaceLine.test(textArray[i])) { // If it is not a line of whitespace.
filteredTextArray.push(textArray[i].trim()); // Trimming here is fine.
}
}
Run Code Online (Sandbox Code Playgroud)
此时,您的输出可能如下所示:
["Dealing with text nodes is fun.", "Some people just use jQuery."]
Run Code Online (Sandbox Code Playgroud)
无法保证这两个字符串在DOM中彼此相邻,因此将它们连接在一起.join()可能会导致不自然的组合。而是在调用的代码中getTextById(),您需要选择要使用的字符串。
测试输出。
try {
var strings = getTextById("bio");
if (strings === null) {
// Do something.
} else if (strings.length === 1) {
// Do something with strings[0]
} else { // Could be another else if
// Do something. It all depends on the context.
}
} catch (e) {
console.log(e.message);
}
Run Code Online (Sandbox Code Playgroud)
可以.trim()在其中添加内容getStringsFromChildren()以消除开头和结尾的空格(或将一堆空格变成长度为零的字符串(""),但是您如何先验地知道每个应用程序可能需要对文本(字符串)进行的操作一旦找到它,您就不去做,因此将其留给特定的实现,然后让它getStringsFromChildren()通用。
有时可能不需要这种特异性水平target。这太棒了。在这些情况下,请使用简单的解决方案。但是,通用算法使您能够适应简单和复杂的情况。
$('.title').clone() //clone the element
.children() //select all the children
.remove() //remove all the children
.end() //again go back to selected element
.text(); //get the text of element
Run Code Online (Sandbox Code Playgroud)
返回第一个#text节点内容的ES6版本
const extract = (node) => {
const text = Array.from(node.childNodes).find(child => child.NodeType === Node.TEXT_NODE);
return text && text.textContent.trim();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
104124 次 |
| 最近记录: |