简体   繁体   English

如何使用jQuery将节点的所有子节点作为javascript中的数组项

[英]how to get all the children of a node as items of an array in javascript using jQuery

for example I have the following structure: 例如,我有以下结构:

<div class="parent">  
    <div>1st child</div>  
    <div>2nd child</div>  
    <div>3rd child</div>  
    <div>4th child</div>  
</div>

all I want is to have the text of all the children of the parent div as items of an array. 我想要的是将父div的所有子节点的文本作为数组的项目。
the jQuery solution is preferred. jQuery解决方案是首选。

var a = $(".parent").children().map(function() { return $(this).text(); });
function get_this_text() {
    return $(this).text();
}

$(".parent div").map(get_this_text).get()

Here's it on fiddle (see result in your console): http://jsfiddle.net/C6pHS/ 这是小提琴(见控制台中的结果): http//jsfiddle.net/C6pHS/

Optionally to the other answers could also do this if it helps you to see things more clearly. 如果它可以帮助您更清楚地看到事情,也可以选择其他答案。 HTML: HTML:

<div class="parent">  
    <div class="child">1st child</div>  
    <div class="child">2nd child</div>  
    <div class="child">3rd child</div>  
    <div class="child">4th child</div>  
</div>

JQuery: JQuery的:

var childArray = $('.child');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在JavaScript中获取节点的所有子节点 - Get all children of a node in javascript 如何获取数组A和数组B的所有项目并将其保存在数组C中? 使用JavaScript而不使用循环 - How to get all items that are both is array A and B and save them in array C? using javascript without using loops 如何使用Javascript获取所有孩子(即孩子的孩子)? - How do i get all children (ie children of children) with Javascript? 如何使用javascript获取嵌套对象中所有子项的单个属性? - How to get a single property of all children in a nested object using javascript? 如何在fancytree中获取节点的所有子节点? - How to get all children of a node in fancytree? 如何在事件侦听器中将父节点与其所有子节点相关联? jQuery / JavaScript - How do I associate a parent node with all of its children in an event listener? jQuery / JavaScript 如何获取 JavaScript 中所有数组项中存在的公共值元素 - How to get elements of common value present in all items of Array in JavaScript jQuery获取所有节点名称(父节点和子节点) - jQuery get all node names (both parent and children) 如何在Javascript中获取subArray的所有子级 - How to get all children of a subArray in Javascript 如何使用JavaScript / jquery仅获取多维数组中的唯一项? - How to get only unique items in a multidimensional array with JavaScript/jquery?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM