How to select all elements of the same class before - javascript

I have something like this:
<div class="htx">
<div>string</div>
</div>
<div class="htx">
<div>string</div>
</div>
<div class="htx">
<div>otherString</div>
</div>
<div class="htx">
<div>string</div>
</div>
I want to select all htx class elements before that one which contains otherString
var res = $('.htx:contains("otherString")');
var sec = res.prevAll();
This didn't work.

You can use:
var res = $('.htx:contains("otherString")');
var sec = res.prevAll('.htx');

jsfiddle (with the exact code from the question + console.log)
Works as expected, the console.log(sec.toArray()); shows 2 divs you are looking for

Like that,
var res = $('.htx div:contains(otherString)');
var sec = res.prevAll();

Using pure JavaScript you can do this:
Demo on Fiddle
var all = document.getElementsByClassName('htx');
for (i = 0; i < all.length; i++) {
if (all[i].getElementsByTagName('div')[0].innerHTML == 'otherString') {
break
} else {
all[i].style.backgroundColor = 'sienna';
}
}

try this in jquery:
var l = $(".htx").lenght;
var elements ="";
for(var i=i; i<=l; i++)
{
if($(".htx:nth-child('" + i + "')").children("div").text() == "otherString")
break;
else
elements += $(".htx:nth-child('+i+')");
}
Hope this helps.

Related

JS - combining array items together in one item

For example I want to collect some tags (lets say paragraph):
var tagsCollection = document.getElementsByTagName('p');
var tagsCollectionLength = tagsCollection.length
I loop through (iterate):
for (var i = 0; i < tagsCollectionLength; i++)
{
//get an array:
var tagsCollectionArray = tagsCollection[i];
}
Now what to do to get all array items as ONE item:
so it won't looks like:
[paragraph1, paragraph2, paragraph3]
but like:
[paragraph1paragraph2paragraph3]
I did try join. concat. etc. without success probably I'm doing something wrong, any help is appreciated. Thanks.
you can keep a variable outside the for, append the strings inside for and when for finishes, push it inside an array.
Here's how to do that -
var tagsCollection = document.getElementsByTagName('p');
var tagsCollectionLength = tagsCollection.length;
var tags = "", tagsCollectionArray = [];
for (var i = 0; i < tagsCollectionLength; i++)
{
tags = tags + tagsCollection[i];
}
tagsCollectionArray.push(tags);
Suppose you have this html
<div>
<p>a</p>
<p>b</p>
<p>c</p>
<p>d</p>
<p>e</p>
</div>
Assuming the result you want is an Array of all the paragraphs's content ([paragraph1paragraph2paragraph3]), then you could do the following:
tagsCollection = document.getElementsByTagName('p');
var ar = [];
for(var i = 0; i < tagsCollection.length; i++ ) {
ar.push(tagsCollection[i].innerText)
}
console.log([ar.join('')]) // => ["abcde"]
See this fiddle
As I have already commented, you can use Array.join("").
JSFiddle.
(function() {
var data = [];
var str = [].map.call(document.getElementsByTagName('p'), function(item) {
return item.innerHTML;
}).join("");
data.push(str);
document.write("<pre>" + JSON.stringify(data) + "</pre>");
})()
<p>hello</p>
<p>workd</p>
<p>test</p>

If data attribute above X number add class to element

I need to add Class highpc to each element with the data attribute of procent, which is bigger than 51. I've got a jQuery solution, but I need it in pure JavaScript. Can anyone help me? This is what I got so far:
HTML
<span data-procent="4" class="procent">4%</span>
<span data-procent="59" class="procent">59%</span>
JS
function highpc(){
var procent = this.elem.getAttribute("data-procent");
if (parseInt(procent) > 51) {
procent.className=procent.className+" highpc";
}
}
window.onload = highpc();
http://jsfiddle.net/Zc8vY/1/
You haven't specified what is this.elem, and you haven't loop in your script.
You are also using variable procent for getting the data-attribute from your element. Later, you are trying to use it for linking the element. Try updated code:
function highpc(){
var elements = document.getElementsByClassName('procent');
for(i=0;i<elements.length;i++) {
var procent = elements[i].getAttribute("data-procent");
if (parseInt(procent) > 51) {
elements[i].className=elements[i].className+" highpc";
}
}
}
Updated fiddle http://jsfiddle.net/Zc8vY/4/
This is your fixed function:
function highpc() {
var elements = document.querySelectorAll('.procent');
for (var i = 0; i < elements.length; i++) {
var procent = elements[i].getAttribute("data-procent");
if (parseInt(procent) > 51) {
elements[i].className += " highpc";
}
}
}
window.onload = highpc;
Note the last line: you don't need () after highpc because you want window.onload to be a reference to a function, not a result of execution.
References: querySelectorAll to select elements.
Demo: http://jsfiddle.net/Zc8vY/3/
Using pure javascript and implementing own getElementsByClassName.
function getElementsByClass(className){
var celems = new Array();
var elems = document.getElementsByTagName("*");
for(var i = 0; i < elems.length;i++){
if(elems[i].className.indexOf(className) != -1){
celems.push(elems[i]);
}
}
return celems;
}
function highpc(){
var elems = getElementsByClass("procent");
console.log(elems);
for(var i = 0; i < elems.length; i++){
highpc_ex(elems[i]);
}
}
function highpc_ex(elem){
var procent = elem.getAttribute("data-procent");
if (parseInt(procent) > 51) {
elem.className=elem.className+" highpc";
}
}
window.onload = highpc();
WORKING FIDDLE HERE
function highpc() {
var aSpans = document.getElementsByTagName("span");
for(var i = 0; i < aSpans.length; i++) {
var eSpan = aSpans[i];
var procent = eSpan.getAttribute("data-procent");
if (procent != null && parseInt(procent) > 51) {
eSpan.className += " highpc";
}
}
}
This is a similar variant to what others have already posted. You might find this one to be more performant for larger sets of html.
Ref: Why .getElementsByTagName() is faster than .querySelectorAll()

Replace a space within a SPAN tag with a BR tag

I need to replace the space between the 2 words with a BR tag. I've tried quite a few things, this one I thought would work, but the original script only does it to the first item. :( I need it to replace it on all the menu items.
It's for menu text on a CMS, so I won't know what the text is going to be. All I know is that it will always be no more than 2 words.
I can use either JS or jQuery.
Demo here: JS Bin Link
HTML:
<span class="navtext">Lorem ipsum</span>
<br>
<span class="navtext">Lorem ipsum</span>
<br>
<span class="navtext">Lorem ipsum</span>
JavaScript:
// Doesnt work
// var span = document.getElementsByTagName(".navtext");
// Only works for the first one
var span = document.querySelector(".navtext");
// Doesnt work
// var span = document.querySelectorAll("navtext");
function space() {
var elem = document.createElement("br");
// elem.className = "space";
// elem.textContent = " ";
return elem;
}
function replace(elem) {
for(var i = 0; i < elem.childNodes.length; i++) {
var node = elem.childNodes[i];
if(node.nodeType === 1) {
replace(node);
} else {
var current = node;
var pos;
while(~(pos = current.nodeValue.indexOf(" "))) {
var next = current.splitText(pos + 1);
current.nodeValue = current.nodeValue.slice(0, -1);
current.parentNode.insertBefore(space(), next);
current = next;
i += 2;
}
}
}
}
replace(span);
I think, you dont want to use jQuery. Well, Here is quick solution:
var elms = document.querySelectorAll(".navtext");
for(var i=0; i<elms.length; i++){
elms[i].innerHTML = elms[i].innerHTML.replace(/\s/gi, "<br />");
}
Here is the jsfiddle: http://jsfiddle.net/ashishanexpert/NrTtg/
using jQuery you can do this:
$("span.navtext").each(function(){
$(this).html($(this).text().replace(/ /g,"<br />"));
})
If you install jQuery you can make it all more simple. Follow the installation instructions and then the code you'll need is something like:
jQuery(function($) {
// for each navtext run the described function
$(".navtext").each(function() {
// "this" represents the navtext
// replace all " " with "<br/>" from this's html
var code = $(this).text();
code = code.replace(" ", "<br/>");
// update this's html with the replacement
$(this).html(code);
});
});
Someone on twitter provided me with a fix, which was exactly like what Ashish answered.
var spans = document.getElementsByTagName("span");
for(var i = 0; i < spans.length; i++) {
spans[i].innerHTML = spans[i].innerHTML.replace(' ', '<br>');
}
But that would quite work for me, but it did give me my answer! So thanks to Pete Williams
This is the code I went with:
var spans = document.querySelectorAll('.navtext');
for(var i = 0; i < spans.length; i++) {
spans[i].innerHTML = spans[i].innerHTML.replace(' ', '<br>');
}

Instantiate new element class using javascript

How can I instantiate an existing div element using javascript? Lets say I have:
<div class="container">
<div class="myclass">TROLL FACE</div>
</div>
I want to create as many 'myclass' element inside the 'container' class as I want using javascript. How can I do this?
Please help, thanks.
You may want the .clone method.
var ele = $('.myclass');
for (var i = 0; i < 5; i++) {
ele.clone().appendTo('.container');
}
The live demo.
var container = $('.container');
for (var i = 0; i < 5; i++) {
container.append('<div class="myclass">TROLL FACE</div>');
}
You could use the .append() method.
With or without JQuery:
for (var i = 0; i < howMany; ++i) {
// pure js
var div = document.createElement('div')
div.classList.add('myclass')
somePlace.appendChild(div)
// jquery
$("<div></div>").addClass('myclass').appendTo(somePlace)
}
Try this
<div class="container">
<div class="myclass">TROLL FACE</div>
</div>
var $container = $('.container');
var $myclass = $('.container').html();
var mycount ; // Your count
for(var i =0;i< mycount ; i++){
$container.append($myclass)
}

Continuously loop through JavaScript text array onclick

I have a text array. I want to display the first entry on page load. And then replace the text with the next entry when I click a button. If I keep clicking the button I want the text to continuously be replaced by waht is next in the array, and when it gets to the end start back at the first entry. Can someone please show me an example code for that. I am new to this.
Here's what I have
$(document).ready(function(){
var arr = new Array("One","Two","Three");
var len=arr.length;
$('#next').click(function(){
for(var i=0; i<len; i++) {
$('#quote').html(arr[i]);
}
});
});
Something like the following should do the trick:
<script type="text/javascript">
var nextWord = (function() {
var wordArray = ['fe','fi','fo','fum'];
var count = -1;
return function() {
return wordArray[++count % wordArray.length];
}
}());
</script>
<p id="foo"> </p>
<button onclick="
document.getElementById('foo').innerHTML = nextWord();
">Update</button>
Edit
Radomised version:
var nextWord = (function() {
var wordArray = ['fe','fi','fo','fum'];
var copy;
return function() {
if (!copy || !copy.length) copy = wordArray.slice();
return copy.splice(Math.random() * copy.length | 0, 1);
}
}());
The following should do it http://jsfiddle.net/mendesjuan/9jERn/1
$(document).ready(function(){
var arr = ["One","Two","Three"];
var index = 0;
$('#next').click(function(){
$('#quote').html(arr[index]);
index = (index + 1) % arr.length ;
});
});
Your code was writing all three values each time you clicked it (but only displaying that last value)
I think something like this would work
The javascript would look like:
// assuming maxTextArrayIndex & textArray are defined & populated
var textDisplayIndex = -1;
document.getElementById('textDisplay').innerHTML = textArray[textDisplayIndex];
function nextElement()
{
textDisplayIndex += 1;
if (textDisplayIndex > maxTextArrayIndex)
{
textDisplayIndex = 0;
}
document.getElementById('textDisplay').innerHTML = textArray[textDisplayIndex];
}
The html would look like:
<body onLoad=nextElement()>
...
<elementToDisplayText id=textDisplay></elementToDisplayText>
<button onClick=nextElement()>Next</button>

Categories

Resources