ejemplo javascript unobtrusive-javascript

javascript - ejemplo - getelementsbytagname



Cómo encontrar a todos los hermanos del objeto seleccionado actualmente (8)

Aquí hay una forma muy corta y sencilla de hacerlo con ES6:

function getAllSiblings(element, parent) { const children = [...parent.children]; return children.filter(child => child !== element); }

Esto devolverá todos los elementos secundarios del nodo principal que no son el elemento.

¿Cuál es la manera perfecta de encontrar todas las siguientes configuraciones y configuraciones anteriores en javascript? Probé varias maneras pero no obteniendo una solución precisa. Si se selecciona algún elemento, necesito obtener la longitud de todos los próximos hermanos, excepto los espacios en blanco, cualquier espacio o saltos de línea.

Además, no quiero usar jquery para esto, específicamente estoy buscando algo del script java

Por favor aconséjame


Esta es una actualización de la respuesta de @ subhaze.

Este código utiliza el método DOM que es compatible con los navegadores modernos :

Demo

function matches(elem, filter) { if (elem && elem.nodeType === 1) { if (filter) { return elem.matches(filter); } return true; } return false; } // this will start from the current element and get all of // the next siblings function getNextSiblings(elem, filter) { var sibs = []; while (elem = elem.nextSibling) { if (matches(elem, filter)) { sibs.push(elem); } } return sibs; } // this will start from the current element and get all the // previous siblings function getPreviousSiblings(elem, filter) { var sibs = []; while (elem = elem.previousSibling) { if (matches(elem, filter)) { sibs.push(elem); } } return sibs; } // this will start from the first child of the current element''s // parent and get all the siblings function getAllSiblings(elem, filter) { var sibs = []; elem = elem.parentNode.firstChild; while (elem = elem.nextSibling) { if (matches(elem, filter)) { sibs.push(elem); } } return sibs; }

Utilice estas funciones de la siguiente manera:

var elem = document.querySelector(''#test''); // find all the "div" and "span" siblings var after = getNextSiblings(elem, ''div, span''); // find previous siblings with ".list-item" class var index = getPreviousSiblings(elem, ''.list-item''); // get all siblings with a title attribute var allSibs = getAllSiblings(elem, ''[title]'');


Esta respuesta fue publicada anteriormente here en respuesta a una pregunta similar.

Hay algunas maneras de hacerlo.

Cualquiera de los siguientes debe hacer el truco.

// METHOD A (ARRAY.FILTER, STRING.INDEXOF) var siblings = function(node, children) { siblingList = children.filter(function(val) { return [node].indexOf(val) != -1; }); return siblingList; } // METHOD B (FOR LOOP, IF STATEMENT, ARRAY.PUSH) var siblings = function(node, children) { var siblingList = []; for (var n = children.length - 1; n >= 0; n--) { if (children[n] != node) { siblingList.push(children[n]); } } return siblingList; } // METHOD C (STRING.INDEXOF, ARRAY.SPLICE) var siblings = function(node, children) { siblingList = children; index = siblingList.indexOf(node); if(index != -1) { siblingList.splice(index, 1); } return siblingList; }

FYI: La base de código de jQuery es un gran recurso para observar Javascript de Grade A.

Aquí hay una herramienta excelente que revela la base de código de jQuery de una manera muy ágil. http://james.padolsey.com/jquery/


Esto es un poco más de una solución, pero le permite crear un filtro sobre cómo conseguir hermanos.

Hay tres funciones para obtener solo la anterior, solo la siguiente o todas . Esto podría mejorarse pero sería un buen punto de partida si necesita más control sobre los tipos de hermanos que desea reunir. Pensé que valdría la pena agregar.

Ejemplo de trabajo

conseguir todos los próximos hermanos

//this will start from the current element and get all of the next siblings function getNextSiblings(elem, filter) { var sibs = []; while (elem = elem.nextSibling) { if (elem.nodeType === 3) continue; // text node if (!filter || filter(elem)) sibs.push(elem); } return sibs; }

obtener todos los hermanos anteriores

//this will start from the current element and get all the previous siblings function getPreviousSiblings(elem, filter) { var sibs = []; while (elem = elem.previousSibling) { if (elem.nodeType === 3) continue; // text node if (!filter || filter(elem)) sibs.push(elem); } return sibs; }

conseguir todos los hermanos

//this will start from the first child of the current element''s parent and get all the siblings function getAllSiblings(elem, filter) { var sibs = []; elem = elem.parentNode.firstChild; do { if (elem.nodeType === 3) continue; // text node if (!filter || filter(elem)) sibs.push(elem); } while (elem = elem.nextSibling) return sibs; }

filtro de ejemplo para aplicar a las funciones anteriores

// Example filter only counts divs and spans but could be made more complex function exampleFilter(elem) { switch (elem.nodeName.toUpperCase()) { case ''DIV'': return true; case ''SPAN'': return true; default: return false; } }

HTML y salida de prueba

HTML

<div id=''test''> <div id=''test2''>asdf</div> <br /> sdf <div>asdfasdf<span>asdf</span></div> <div>a</div> <span>a</span> <br /> <div>d</div> <hr/> </div>

JavaScript

var elem; elem = document.getElementById(''test2''); //with filter alerts 4 alert( getNextSiblings( elem, exampleFilter ).length ); // no filter, alerts 7 elem = document.getElementById(''test2'');// put elem back to what it was alert( getNextSiblings( elem ).length ); // alerts 0 elem = document.getElementById(''test2'');// put elem back to what it was alert( getPreviousSiblings( elem, exampleFilter ).length ); // alerts 5 elem = document.getElementById(''test2'');// put elem back to what it was alert( getAllSiblings( elem, exampleFilter ).length );


Puede obtener todos los elementos secundarios del elemento primario del elemento y excluir el elemento en sí.


Sólo mis dos centavos aquí, hice un par de funciones para obtener todas las previos y los siguientes hermanos de cualquier elemento.

const getPreviousAll = element => { const previousAllFound = []; const getPrevious = element => { if (element !== null) { previousAllFound.push(element); const previousFound = element.previousElementSibling; if (previousFound !== null) { getPrevious(previousFound); } } }; getPrevious(element.previousElementSibling); return previousAllFound; }; const getNextAll = element => { const target = element; const nextAllFound = []; const getAll = element => { if (element !== null) { nextAllFound.push(element); const nextFound = element.nextElementSibling; if (nextFound !== null) { getAll(nextFound); } } }; getAll(element.nextElementSibling); return nextAllFound; };

Solo tiene que llamar a estas funciones con un nodo que puede obtener por getElementById.


de vuelta a 2017:
Tal vez haya una respuesta mejor pero que buena y un poco más limpia.

function sibiling(dom, query) { var doms = dom.parentElement.querySelectorAll(query); return [].slice.call(doms).filter( d => d != dom); }


Asumiré que esto ocurre dentro de un controlador de eventos donde se trata de una referencia al elemento objetivo cuyos hermanos desea afectar.

Si no, se necesitarán ajustes.

var result = [], node = this.parentNode.firstChild; while ( node ) { if ( node !== this && node.nodeType === Node.ELEMENT_NODE ) result.push( node ); node = node.nextElementSibling || node.nextSibling; } // result will contain all type 1 siblings of "this"