I have a bunch of span4 class elements in my html. they look something like this:
<div class="span4">
<div class="widget">
<div class="header">blablabla</div>
</div>
</div>
I want to sort the span4 by that text iside header class.
I do this to sort them
$(".span4").sort(sortAlpha)
but how do I select the text inside the header class?
I'm doing this but I guess there is a better way
function sortAlphaAsc(a,b){
var nomeA = $(a.childNodes[1].childNodes[1]).text();
var nomeB = $(b.childNodes[1].childNodes[1]).text();
return a.innerHTML.toLowerCase() > b.innerHTML.toLowerCase() ? 1 : -1;
};
there must be a better way than
$(a.childNodes[1].childNodes[1]).text()
var elems = $(".span4");
elems.sort(function(a, b) {
return $(a).find('.header').text().toUpperCase().localeCompare(
$(b).find('.header').text().toUpperCase()
);
});
$(".span4").parent().html(elems);
FIDDLE
Try this:
function sortAlphaAsc(a,b){
var nomeA = $(a).find('div.header').text();
var nomeB = $(b).find('div.header').text();
return nomeA.toLowerCase() > nomeB.toLowerCase();
};
You could detach the spans, sort and append them.
That will be very fast too as changing elements in memory and only updating the DOM once in the end is very efficient.
var $spans = $(".span4").detach();
var sortedSpans = $spans.sort(function(spanA, spanB) {
var spanTextA = $("div.header", spanA).text();
var spanTextB = $("div.header", spanB).text();
return spanTextA > spanTextB;
});
$("body").append(sortedSpans);
Obviously instead of body you append it back to it's actual container element.
Or if the spans are in a common container store the parent in cache var $parent = $spans.parent() and in the end simply do $parent.html(sortedSpans).
I don't know your whole mark-up but that should get you started.
DEMO - Detach spans, sort them and append again
Do you mean something like this:
$('.span4').find('.header').text();
This will return the text inside the header div.
Related
JSFiddle here
Hi! I'm trying to output a string from the .contents().text() of an element... but with spaces between the content of each div (without changing the actual DOM).
HTML:
<!-- I don't have control over how many divs are in .myTextArea, or what text. It's really dynamic. There are also lists, etc.--tons of different types of elements. -->
<div class="myTextArea">
<div>Hey there!</div><div>I like turtles.</div><div>Do you like them?</div>
</div>
jQuery:
var myTextDescription = $(".myTextArea").contents().text();
console.log(myTextDescription);
Currently, it outputs:
Hey there!I like turtles.Do you like them?
...and this is what I want it to output: The same thing, but with spaces after the content of each div:
Hey there! I like turtles. Do you like them?
Note: Other answers on SO make you change the actual DOM (AKA, they add actual spaces after the elements on the page), and then they just grab the text() string. I don't want to change the DOM.
Also, I can't use .html() instead and try to strip away stuff, because there will be wayyyyyy too many types of elements to worry about.
JSFiddle here
You're almost there. Replace .text() with:
//get text content of all nodes
.map((i,d) => d.textContent).get()
//remove white space
.filter(t => !!t.trim())
//join the text from all nodes with a space
.join(' ');
Check out the demo below:
var myTextDescription = $(".myTextArea").contents().map((i,d) => d.textContent).get().filter(t => !!t.trim()).join(' ');
console.log(myTextDescription);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="myTextArea">
<div>Hey there!</div><div>I like turtles.</div><div>Do you like them?</div>
</div>
In case you needed to exclude text in a div, say with a class exclude you can use the :not() psedo selector like so:
... .contents(':not(".exclude")') ....
..as in the demo below:
var myTextDescription = $(".myTextArea").contents(':not(".exclude")').map((i,d) => d.textContent).get().filter(t => !!t.trim()).join(' ');
console.log(myTextDescription);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="myTextArea">
<div>Hey there!</div><div class="exclude">Please exclude this!</div><div>I like turtles.</div><div>Do you like them?</div><div class="exclude">Please exclude this too!</div>
</div>
One way to solve this is to use JavaScript's querySelectorAll method to return a list of all the DIVs in your myTextArea element. You can then run through each element in the list, get its innerText and place a space after each one:
var myTexts = document.querySelectorAll('.myTextArea > div');
var show = document.querySelector('#show');
var output = "";
for (var x = 0; x < myTexts.length; x++) {
if (output == "") { // Skip adding space before first string
output = myTexts[x].innerText;
} else { // Add space before each appended string
output += " " + myTexts[x].innerText;
}
}
show.innerText = output;
<div class="myTextArea">
<div>Hey there!</div>
<div>I like turtles.</div>
<div>Do you like them?</div>
</div>
<div id="show"></div>
I'd like to select an element using javascript/jquery in Tampermonkey.
The class name and the tag of the elements are changing each time the page loads.
So I'd have to use some form of regex, but cant figure out how to do it.
This is how the html looks like:
<ivodo class="ivodo" ... </ivodo>
<ivodo class="ivodo" ... </ivodo>
<ivodo class="ivodo" ... </ivodo>
The tag always is the same as the classname.
It's always a 4/5 letter random "code"
I'm guessing it would be something like this:
$('[/^[a-z]{4,5}/}')
Could anyone please help me to get the right regexp?
You can't use regexp in selectors. You can pick some container and select its all elements and then filter them based on their class names. This probably won't be super fast, though.
I made a demo for you:
https://codepen.io/anon/pen/RZXdrL?editors=1010
html:
<div class="container">
<abc class="abc">abc</abc>
<abdef class="abdef">abdef</abdef>
<hdusf class="hdusf">hdusf</hdusf>
<ueff class="ueff">ueff</ueff>
<asdas class="asdas">asdas</asdas>
<asfg class="asfg">asfg</asfg>
<aasdasdbc class="aasdasdbc">aasdasdbc</aasdasdbc>
</div>
js (with jQuery):
const $elements = $('.container *').filter((index, element) => {
return (element.className.length === 5);
});
$elements.css('color', 'red');
The simplest way to do this would be to select those dynamic elements based on a fixed parent, for example:
$('#parent > *').each(function() {
// your logic here...
})
If the rules by which these tags are constructed are reliably as you state in the question, then you could select all elements then filter out those which are not of interest, for example :
var $elements = $('*').filter(function() {
return this.className.length === 5 && this.className.toUpperCase() === this.tagName.toUpperCase();
});
DEMO
Of course, you may want initially to select only the elements in some container(s). If so then replace '*' with a more specific selector :
var $elements = $('someSelector *').filter(function() {
return this.className.length === 5 && this.className.toUpperCase() === this.tagName.toUpperCase();
});
You can do this in vanilla JS
DEMO
Check the demo dev tools console
<body>
<things class="things">things</things>
<div class="stuff">this is not the DOM element you're looking for</div>
</body>
JS
// Grab the body children
var bodyChildren = document.getElementsByTagName("body")[0].children;
// Convert children to an array and filter out everything but the targets
var targets = [].filter.call(bodyChildren, function(el) {
var tagName = el.tagName.toLowerCase();
var classlistVal = el.classList.value.toLowerCase();
if (tagName === classlistVal) { return el; }
});
targets.forEach(function(el) {
// Do stuff
console.log(el)
})
I would like to wrap the live content of a DOM element into another, keeping all the structure and all attached event listeners unchanged.
For example, I want this
<div id="original">
Some text <i class="icon></i>
</div>
to become
<div id="original">
<div id="wrapper">
Some text <i class="icon></i>
</div>
</div>
Preferably without jQuery.
If there is nothing else other than ID to distinguish your nodes, and given that #original has multiple child nodes, it would probably be simpler to create a new parent node and insert that:
var original = document.getElementById('original');
var parent = original.parentNode;
var wrapper = document.createElement('DIV');
parent.replaceChild(wrapper, original);
wrapper.appendChild(original);
and then move the IDs to the right place:
wrapper.id = original.id;
original.id = 'wrapper';
noting of course, that the variables original and wrapper now point at the 'wrong' elements.
EDIT oh, you wanted to leave the listeners attached... Technically, they still are, but they're now attached to the inner element, not the outer one.
EDIT 2 revised answer, leaving the event listeners attached to the original element (that's now the outer div):
var original = document.getElementById('original');
var wrapper = document.createElement('DIV');
wrapper.id = 'wrapper';
while (original.firstChild) {
wrapper.appendChild(original.firstChild);
}
original.appendChild(wrapper);
This works simply by successively moving each child node out of the original div into the new parent, and then moving that new parent back where the children were originally.
The disadvantage over the previous version of this answer is that you have to iterate over all of the children individually.
See https://jsfiddle.net/alnitak/d0jss2yu/ for demo
Alternatively, do it this way. It also displays result in the adjacent result div.
<div id="original">
Some text <i class="icon"></i>
</div>
<button onclick="myFunction()">do it</button>
<p type="text" id="result"></p>
<script>
function myFunction() {
var org = document.getElementById("original");
var i = org.innerHTML; //get i tag content
var wrap = document.createElement("div"); //create div
wrap.id="wrapper"; //set wrapper's id
wrap.innerHTML= i //set it to i tag's content
org.innerHTML=""; // clear #orignal first
org.appendChild(wrap); //append #wrapper and it's content
var result = org.outerHTML;
document.getElementById("result").innerText = result;
}
</script>
Updated answer:
This should work better and with less code than my previous answer.
var content = document.getElementById("myList").innerHTML;
document.getElementById("myList").innerHTML = "<div id='wrapper'></div>"
document.getElementById("wrapper").innerHTML = content;
EDIT: This will destroy any event listener attached to the child nodes.
Previous answer:
I don't tried it, but something like this should work:
var wrapper = document.createElement("DIV");
wrapper.id = "wrapper";
var content = document.getElementById("myList").childNodes;
document.getElementById("myList").appendChild(wrapper);
document.getElementById("wrapper").appendChild(content);
Create the wrapper element.
Get myList contents.
Add the wrapper element to myList.
Add myList contents to be child of the wrapper element.
Hello I want to get the nodes of class "ms-qSuggest-listItem" from the id.
<div class="ms-qSuggest-list" id="ctl00_ctl38_g_c60051d3_9564_459e_8a40_e91f8abf4dcf_csr_NavDropdownList" style="width: 508px;">
<div class="ms-qSuggest-listItem">Everything</div>
<div class="ms-qSuggest-listItem">Videos</div>
<div class="ms-qSuggest-hListItem">People</div>
<div class="ms-qSuggest-listItem">Conversations</div>
</div>
I tried
var nodes = $get("ctl00_ctl38_g_c60051d3_9564_459e_8a40_e91f8abf4dcf_csr_NavDropdownList").class(ms-qSuggest-listItem);
If I wanna get the nodes from its direct class - here its working but I want to get it from the ID.
var nodes = $("div.ms-qSuggest-listItem");
Please help.
Thanks.
All the below selectors will give you the matching nodes.
var nodes = $("#ctl00_ctl38_g_c60051d3_9564_459e_8a40_e91f8abf4dcf_csr_NavDropdownList").find('.ms-qSuggest-listItem');
OR
var nodes = $("#ctl00_ctl38_g_c60051d3_9564_459e_8a40_e91f8abf4dcf_csr_NavDropdownList .ms-qSuggest-listItem");
OR
var nodes = $(".ms-qSuggest-listItem", "#ctl00_ctl38_g_c60051d3_9564_459e_8a40_e91f8abf4dcf_csr_NavDropdownList");
Demo: https://jsfiddle.net/tusharj/fr2d9yv1/
You can use the id in conjunction with the class name within the same selector like this:
var long_id = 'ctl00_ctl38_g....';
var nodes = $('#' + long_id + ' .ms-qSuggest-listItem');
Basically what is happening here is the selector is matching the id and then looking inside it's children for the specified class name.
A more explicit way of writing this would be to use the .find() function on the parent node itself.
Description: Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
var long_id = 'ctl00_ctl38_g....';
var parent_node = $('#' + long_id);
var children_nodes = parent_node.find('.ms-qSuggest-listItem');
JSFiddle demo
I have this html code.
<div class="breadcrumb">
Home
<a class="breadcrumb" href="#">About</a>
<a class="breadcrumb" href="#">History</a>
Message from our Founding Members
</div>
Using javascript I want to get the text from the div ".breadcrumb". The problem is the a tag under the div also has a class with the same name, when I run this code:
var names = document.querySelectorAll('.breadcrumb');
return [].map.call(names, function(name) {
return name.textContent;
});
My first element of the array gets the textContent of all the a elements and also the div.
How can I do to get the text of only the div. In this case I want to return only "Message from our Founding Members".
Is there a way to select only the root item of the html, when they have all the same class ?
Thanks
If you want to get the text from the <a> tags with the class="breadcrumb", you can do that by using more specific selectors that include the tag type like this:
var items = document.querySelectorAll("div.breadcrumb a.breadcrumb");
var text = [];
for (var i = 0; i < items.length; i++) {
text.push(items[i].textContent);
}
Working demo: http://jsfiddle.net/jfriend00/kVwH8/
If, what you're trying to do is to get the "Message from our Founding Members" text (I wasn't entirely clear from your original question), then you can do that like this::
var items = document.querySelectorAll("div.breadcrumb a.breadcrumb");
// get node after the last item (that should be the desired text node)
var txtNode = items[items.length - 1].nextSibling;
console.log(txtNode.nodeValue); // Message from our Founding Members
Working demo: http://jsfiddle.net/jfriend00/kynuE/
use div.breadcrumb because that will give you divs with class breadcrumb, not a tags.
You can do this:
var names = document.querySelectorAll('div.breadcrumb')[0].childNodes;
var text = Array.prototype.reduce.call(names,function(prev,node){
if(node.nodeType === 3) return (prev || '' + node.textContent.trim());
});
console.log(text);
There are a lot of ES5 stuff here like trim and reduce so better have those polyfills handy.