'Best' way to pull data relative to a div? - javascript

This answer suggested i should put my data in JS instead of a textarea.
Thinking about it i could have scripts and do something like myarray[i]="data" where i is the index of my for loop. However when i click a div how do i find out what i is? I have used var data = $(this).parent('.parent').find('.valuestr').eq(0).val(); which is extremely simple. Should i use a script or should i continue to do it with a textarea? if i should use a script 1) Whats the easiest way to find i and 2) Is it bad pratice to have dozens or hundreds of <script> in my html? or i can go through the loop twice but i still dont know the easiest way to find i. I would have to store it somewhere or go through multiple tags and count them.

Answering the other part of your question:
2) Is it bad pratice to have dozens or
hundreds of in my html?
It will depend on who you talk to, but in general, yes, I think it is. There's actually a push for html to be completely devoid of Javascript, save loading of .js files. For more info, look into unobtrusive javascript.
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript

jQuery has a data() function just for that.
You store arbitrary data related to some element like this:
$('#my_div').data('foo', 'bar');
$('#my_div').data('hello', 'world');
Then you retrieve it like this:
alert($('#my_div').data('foo')); // alerts "bar".
alert($('#my_div').data('hello')); // alerts "world".

Since each DOM_Element is just an object, you can declare a variable in the object.
for(var i = 0; i < elements.length; i++)
{
elements[i].i = i;
elements[i].onclick = function(){
alert(this.i);
}
}

Related

How to use JavaScript to get all element from a dynamic scroll list?

Like the title said, how do I get all elements from a scroll div? The elements in the scroll list are loaded and destroyed dynamically.
I tried to crawl all course names from this website:
https://public.enroll.wisc.edu/search?term=1204
The code below only works for one time:
let list = document.getElementsByClassName('md-virtual-repeat-scroller')[0]
let childs = document.getElementsByClassName("result__name")
console.log(childs[0].innerText)
However, if I do this, I will get the same result for 10 times:
let list = document.getElementsByClassName('md-virtual-repeat-scroller')[0]
for(let i = 0; i < 10; i++) {
let childs = document.getElementsByClassName("result__name")
for(let j = 0; j < childs.length; j++) {
console.log(childs[j].innerText)
}
// scroll by 1000px every time
list.scrollBy(0, 1000)
}
I don't know what's the problem. Is it because that scrollBy() works asynchronously? But I tried to use async and await. It still doesn't work.
Give more information in less words as a possible. Many problems could be related to browser and its version, for example. How is this script called? Are you giving commands via browser console? Have you done a copy of the site and performed some modification on it? It's hard to understand the problem in a realistic level.
Tip: Avoiding use innerText. It's slower and is supported in many browsers only for compability to scripts written to old versions of IE. (I don't know why so many examples in internet use it as first option). User textContent instead.
It's always good to test the returned value of a function/methods - specially during the development of the program.
Never ask to the StackOverFlow community (and to any other) to write progams for you!
You question "how do I get all elements from a scroll div?" is so "loose". scroll div? The answer to this, independently to the "type of div" (and tag!) would be found below.
Your code seems to be no sense in order to do what you want. Why iterate from 0 to 10?
Look at this snipet. I think it will help you
const list = document.getElementsByClassName('md-virtual-repeat-scroller')[0];// if there is no intention to reassign it. Use [0] if you are sure it's the first element of this collection
let childs = list.getElementsByClassName("result__name"); // get only elements inside the first variable!
Use the iterator of the variable.
for(item of childs)
{
/*code*/
}
I am sure you will achieve your goals!
And never suggest us (Community) to code for you or even to resolve your problem. This sound very agressive! To you too! I'm sure.
I solved my problem by reading this article:https://intoli.com/blog/scrape-infinite-scroll/
The reason why I kept getting the same elements is that scrollBy() works asynchronously, so I have to wait then evaluate the page again. I am using puppeteer by the way.
please read the article, super helpful.

Is it possible to read the original internal stylesheet rules via jQuery after they have been changed with jQuery?

I feel a bit ridiculous even asking, but some of the research I have done makes me think that it might be possible?
Say I have an internal CSS rule like this:
<style>div {width 50px;}</style>
And then I use jQuery to change the value of the width of the div like this:
$('div').css({"width":"100px"});
Is it possible to retrieve the original width of 50px from the original CSS rules using JavaScript?
Or is the only way to first save the original width value of 50px in a javascript variable and retrieve it later using that same variable?
In theory... the original values are all still contained and accessible via the source code of the page... and I don't really care to go that far (to write a CSS parser in javascript).
Or does the source of the page cease to exist basically when the browser renders the DOM?
Thanks for reading.
Not possible as far as I know. As Barmar said, easiest way would be to remove the style, get the original value, then add the style again.
Something like this should work:
function getOriginalCSS(target,styles){
var output = {}
for(var i=0; i<styles.length; i++){
var style = styles[i]
var current = target.css(style)
target.css(style,'')
output[style] = target.css(style)
target.css(style,current)
}
return output
}
Calling getOriginalCSS($('div'),['width']) should give you {width:'50px'}
The easiest way would be to save the previous value before you change the CSS and then re-apply the old value when you need.
Any other way would be tedious and frankly not worth the work-around.

Generating HTML via javascript/jquery. Good programming practice?

Is it good practice to generate HTML through Javascript/Jquery like this:
$('<input></input>', {
'id': this.elements.verticalPanel.layout2,
'type': 'button',
'value': '2',
'data-toggle': 'tooltip',
/*'title': 'Layout 2',*/
'class': this.elements.verticalPanel.panelElement
})
.tooltip()
.appendTo(div);
This is just a small snippet from my code.
Well the functionality works just fine, but I was curious as to know whether other developers follow this practice ?
Like that is fine in small doses. If you are in a situation where you need to generate a lot of html, there's a much better way to do it.
Basically, build up your html as a string. Then create an in-memory element and set its innerHTML to your string. You can then append the element to somewhere in the DOM, or operate on its child elements (your html) and do whatever needs doing.
Here's a simple, quickly hacked together sample: http://jsfiddle.net/ygL7f/
var sample = ['<ul>'],
els = 1000;
for(var i=1; i<els; i++){
sample[i] = '<li>'+ (Math.random() * 10) +'</li>'
}
sample.push('</ul>');
var root = document.createElement('div');
root.innerHTML = sample.join('');
document.querySelector('body').appendChild(root);
The critical thing to remember when generating lots of html this way is to avoid function calls wherever possible. Function calls are expensive.
In my sample, notice how I'm assigning the html directly to the array index instead of calling sample.push('string'). Faster this way.
I am a web developer for many years. we use this method only for generating dynamic updated html and few html code. sometimes it is difficult to navigate correctly through this newly generated dom . the disadvantage of this method is that user can't load those html if javascript is blocked by the user browser
JQuery can be used to manipulate, and generate, HTML. Good practice would also mean you clearly comment your code and refactor it to simple re-usable components. What you are doing isn't "wrong".
If you need to generate DOM elements dynamically, the alternative to this would be a long sequence of string concatenations. I find this jQuery style far more readable, and I generally use it.

Javascript : how to get value from a Script Tag

I am trying to get the following value from the script below
Use this field to store the Account to which the Opportunity is related
<script>sfdcPage.setHelp('Opportunity.Account', 'Use this field to store the Account to which the Opportunity is related');</script>
i can get to this script tag by using :
document.getElementsByTagName('tbody')[6].getElementsByTagName('script')[1];
Can you please let me know.
Many thanks.
I would not recommend putting script tags within your tables, etc. In other words, I wouldn't mix script tags with other content-related HTML like that. If you want to store little bits of info like that in your HTML for the purpose of JS, I'd use data attributes instead.
The simple answer to your question though is to just use the innerHTML or innerText property as follows:
document.getElementsByTagName('tbody')[6].getElementsByTagName('script')[1].innerHTML;
Use innerHtml as
document.getElementsByTagName('tbody')[6].
getElementsByTagName('script')[1].
innerHtml;
OR
Set an id to get script content as below example
<script id='script' type='text/javascript'>
$('div').html($('#script').html());
console.log($('script'));
</script>
fiddle
There are lots of ways to do this. One solution....
var scrs = document.getElementsByTagName('script');
var newscr = "";
for (var i=0; i<scrs.length; i++) {
newscr = scrs[i].innerHtml.replace('sfdcPage.setHelp(', 'myfunction(');
if (newscr != scrs[i].innerHtml) {
eval(newscr);
}
}
(although parsing / rewriting the javascript is an ugly hack - if it's your code then your reading then you should know what you put in there).

conditionals in javascript based on page currently showing

because of some problems with joomla "in-content javascript" I have to give all my js logic to one file, but there are problems with inconsistence of dom elements across my site (it is ajax driven, so there is only one script and various DOMs).
What is the best solution to make some conditionals solving this problem..
Is it checking $(selector).length, or is there any better solution..
And in case of the $(selector).length , is there a way to save this selector to variable (performance issues)
for example some kind of
var selector = ($(selector).length !== 0) ? this : false ;
if(selector) { makeSomething; }
The this is actually pointing to Window object..So is there any way to make it like this without need of reselection?
Thanks
var $obj = $('selector');
if ($obj.length) { makeSomething(); }
Actually, this is only meaningful if you are searching for the existence of a certain element (that might identify a whole page) and running several operations based on that.
If you just want to do something on the elements like
$('selector').append('x');
the condition might be useless, because if the jQuery collection is empty, the methods won't run anyways (as pointed out by #Gary Green).

Categories