Get the text from a div with a certain condition - javascript

I have a big div containing many divs inside, I need to get the text from those inner divs but at certain condition, something like this:
for (var i = 0; i < g; i++)
{
var h = $('#infor > div').["dataid = i"].text();
alert(h);
}
(infor) is the id for the big div and (dataid) is the attribute of the inner divs

You need to use:
var h = $('#infor > div[dataid = '+ i +']').text();

Related

Different/Increasing CSS Value for Many DIVs With Same Class

I want to use javascript to change the left-margin value of many separate DIVs. The catch is that:
I want to use only one className and
I want the margin to increase, for example, 100px for each instance of the class. This way, instead of having all the DIVs land on top of each other, each DIV will be space out: the first at margin-left:0px, the second at margin-left:100px, the third at margin-left:200px, and so on.
Here is the code that I have which simply applies the same margin-left to all DIVs.
<script>
b = document.getElementsByClassName('spacing');
for (i = 0; i < b.length; i++) {
b[i].style.marginLeft = "100px";
}
</script>
Is there a way to get the javascript to find each instance of the class sequentially and instead of simply applying margin-left:100px to all, it does something like (margin applied to last instance of class + X) so each of 100 DIVs with the same className end up with a unique marginLeft value?
Yes there is a way You can simply multiply the amount of margin by iteration number like this i*100+'px' instead of this "100px"
var b = document.getElementsByClassName('spacing');
for (i = 0; i < b.length; i++) {
b[i].style.marginLeft = i*5+'px';
}
Here is the working example
What you want to do is keeping track of your increasing margin by every iteration of the loop:
b = document.getElementsByClassName('spacing');
var margin = 0;
for (i = 0; i < b.length; i++) {
margin += 100;
b[i].style.marginLeft = margin + "px";
}
That should do the trick.
Check out a working example here: https://jsfiddle.net/c4p9ry46/

Making divs fill up a containing div?

I've been searching the site for an answer, and nothing I've come across seems to help. I'm trying to make it so that a default (and eventually user-specified) number of divs fill up the containing div like a grid. I'm trying to figure out how to make the size of the boxes I append to the parent change depending on how many are added, while always filling up the div, if that makes sense. So for instance, if I specify 9, I should have 3 rows and 3 columns. If I specify 62, then I'm looking for 16 rows and 16 columns, always filling up (or coming close to, anyway) the containing div. Here's a JSfiddle I have so far: https://jsfiddle.net/psyonix/1g9p59bx/1/ Here's the code as it is:
var d = ("<div class='square'></div>");
function createGrid(numSquares){
for(var i = 0; i < numSquares; i++){
$('#g_area').append(d);
}
var squareSize = Math.floor(580/numSquares );
$('.square').height(squareSize);
$('.square').width(squareSize);
};
$(document).ready(function(){
createGrid(64);
});
The only issue you had was setting the square size to 1/64th of the height instead of 1/(64^.5) of the height. Essentially you where just making one row. https://jsfiddle.net/1g9p59bx/7/
var d = ("<div class='square'></div>");
function createGrid(numSquares){
var gridContainer = $('#g_area');
for(var i = 0; i < numSquares; i++){
gridContainer.append(d);
}
var squareSize = Math.floor(580/(Math.sqrt(numSquares)) );
$('.square').height(squareSize);
$('.square').width(squareSize);
};
$(document).ready(function(){
createGrid(64);
});
I would create a little jqueryplugin for that. You can call it in every container you like: containerForGrid.createGrid(cols, rows)
(function($){
$.fn.createGrid = function(cols, rows) {
// get width and height of sorrounding container
var w = this.width()
var h = this.height()
// calculate width and height of one cell
var colWidth = w / cols
var rowHeight = h / rows
// loop over all rows
for(var i = rows; --i;){
// loop over all cols
for(var j = cols; --j;){
$('<div>').css({
width:colWidth,
height:rowHeight,
float:'left'
}).appendTo(this)
}
}
}
})(jQuery)
jQuery('div').createGrid(10,10)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="width:1000px;height:500px">
</div>

How to count the number of line boxes in a DIV or P

<div><span>aaaaaa</span> ... (many other span here) ... <span>zzzzzz</span></div>
In that case, the boxes span are placed on few line-boxes inside the div.
(The span elements can use different font-size.)
1) How can we know the number of the line-boxes ?
2) Can we know on which line-boxe an element span is placed ?
3) Can we know on which line-boxe the caret is placed (contenteditable) ?
Thank you
I'll suppose the DOM in your example is an effective example of the actual complexity of your DOM, and that a "line-boxe" is just a line of text.
1-2) For every <span> inside the <div>, you can count the number of lines they span with something like this:
var spans = div.getElementsByTagName("span"), spandata = [];
for (var i = 0; i < spans.length; i++) {
var rects = spans[i].getClientRects();
if (i > 0)
if (rects[0].bottom > obj.rects[obj.rects - 1].bottom)
var inirow = obj.lastRow + 1;
else var inirow = obj.lastRow;
var obj = {
element: spans[i],
rects: rects,
iniRow: inirow,
lastRow: inirow + rects.length - 1
};
spandata.push(obj);
}
Now spandata is a list of all the data you want about the <span> elements. I'm also supposing that each one of them may span through more than one line.
Keep in mind that getClientRects has some issues in IE<8.
3) In modern browsers, the getSelection method can help you:
var sel = window.getSelection();
if (sel.type === "Caret")
var span = sel.anchorNode.parentNode;
About the line position, I must say it's not an easy task. You can't easily get the page position of the caret. The simplest thing you can do is to place a dummy inline element in the place of the caret:
var text = sel.anchorNode.nodeValue;
sel.anchorNode.nodeValue = text.substring(0, sel.anchorOffset);
var dummy = document.createElement("i");
span.appendChild(dummy);
var pos = dummy.getBoundingClientRect();
sel.anchorNode.nodeValue = text;
span.removeChild(dummy);
pos contains the info of the position of the caret. Now you have to compare them with the rect infos about the span:
var rects = span.getClientRects();
for (var i = 0; i < rects.length; i++)
if (rects[i]].bottom === pos.bottom) break;
if (i < rects.length) {
for (var i = 0; i < spandata.length; i++) {
if (spandata[i].element === span) {
var line = spandata[i].iniRow + i;
break;
}
}
}
In the end, if line != null, it contains the line of the caret.
Man, that was complicated...
Let's say your div is in the el variable:
el.children.length; // Number of direct children
// You have one of the children in the "child" variable, to know its index:
[].indexOf.call( el.children, child ); // Index of child in el.children
I'm not mentioning the cross-browser issues there, but Array.prototype.indexOf is only available starting IE9 (so it works in all modern browsers).

split html content into fixed height and width divs with jQuery

I'm trying to split a large html page into smaller fixed height and width chunks (pages).
Its pretty easy if I know the pages count - I can generate required number of pages first and then fill them with source content children:
children = $('#source').children();
width = 600;
height = 600;
// already generated 'pages'
divs = $('.page');
$(divs).width(width);
pages = divs.length;
i = 0;
for (var c = 0; c < pages; ++c) {
var div = $(divs).eq(c);
while (i < children.length && div.height() < height) {
$(children[i++]).clone().appendTo(div);
}
if(div.height() > height) {
div.contents().last().remove();
i--;
}
}
But how can I do the same thing if I don't know the pages count?
How to wrap content with $('div.page') and keep adding pages until I reach the end of content?
thanks
You would want to use a loop to keep creating pages / filling them with content until you hit some endpoint, where you'd break out of the loop. The key here is dynamically creating the page divs in the loop. You can use document.createElement or simply $("") (or other jQuery ways). Something like this:
var i = 0;
while(true) {
if (content /* have more content */) {
var page = document.createElement("div");
$(page).addClass('page');
var children = $(content).children();
while (i < children.length && div.height() < height) {
$(children[i++]).clone().appendTo(page);
}
$(body).append(page);
} else {
break;
}
}
You may also want to use jQuery's each method if you have defined blocks of content to add to each 'page'.
Comment if you need more help.

appendChild to array only appends to last element

As you can see I am still a novice in javascript
Why is it so that you can append a Textnode only once? When you add it again somewhere else the first one disappears
I do not need a solution to a problem I was just curious what is causing this behavior.
Example where the textnode is only added to the last element of an array:
function hideAdd(){
var hide = document.createTextNode('Afbeelding verbergen');
var afb = collectionToArray(document.getElementsByTagName('img'));
afb.pop();
var divs = [];
for (i=0; i < afb.length; i++){
divs.push(afb[i].parentNode);
}
console.log(divs);
for ( i = 0; i < divs.length;i++){
divs[i].appendChild(hide);
}
}
This is where you use an unique textnode so it works:
function hideAdd(){
var hide = []
var afb = collectionToArray(document.getElementsByTagName('img'));
afb.pop();
var divs = [];
for (i=0; i < afb.length; i++){
divs.push(afb[i].parentNode);
hide[i] = document.createTextNode('Afbeelding verbergen');
}
console.log(divs);
for ( i = 0; i < divs.length;i++){
divs[i].appendChild(hide[i]);
}
}
Short answer is the DOM is a tree, not a network. Each node can have only one parent. If you could add a node in more than one location, it would have more than one parent.

Categories