How to select specific value in a Query in HTML <script> - javascript

I need to know how to select a specific value in a form of a query.
Under the Content.join('');, I need to select like 2 values which is the Hello and Lorem ipsum... then Hi and Nullam fringilla..., and so on.
Sorry, kinda new to this stuff as well.
<script>
var Count = 0;
var title = document.getElementById("getTitle");
var desc = document.getElementById("getDescription");
var Content = [
["Option1", "Hello", "Lorem ipsum dolor sit amet"],
["Option2", "Hi", "Nullam fringilla imperdiet eleifend"],
["Option3", "Greetings", "Cras dapibus ipsum a consequat tincidunt"]];
function previewImg(DibsSrc){
document.getElementById("Dibs").src =DibsSrc.src;
Content[Count][0] = DibsSrc.id;
title.innerhtml = Content.join('');
desc.innerhtml = Content.join('');
}
</script>

Content[0][1] or Content[Count][1] = Hello
Content[0][2] or Content[Count][2] = Lorem ipsum dolor sit amet
To check the next item you need to update the Count var with a +1.
Content[1][1] or Content[Count][1] = Hi
Content[1][2] or Content[Count][2] = Nullam fringilla imperdiet eleifend
Note that the count starts with 0, so your first item is 0 instead of 1.

Related

Array, How i show both title and Description?

I'm having a problem with the array showing the title and description. When I try [0,0] it won't show the title or the description. When I try
var imgCount = 0;
var imgContent = [
["imgOption1", "BOM", "Lorem ipsum dolor sit amet."],
["imgOption2", "DOM", "Nullam fringilla imperdiet eleifend"],
["imgOption3", "JavaScript", "Cras dapibus ipsum a consequat tincidunt"]
];
function previewImg(imgSrc){
document.getElementById("imgViewer").src = imgSrc.src;
alert(imgContent[imgCount][0]= imgSrc.id);
}
Expected Output:
imgOption1 BOM Lorem ipsum dolor sit amet.
Not the output I wanted
imgOption1
The problem is I want to show both title and description that I showed on expected output.
var imgContent = [
["imgOption1", "BOM", "Lorem ipsum dolor sit amet."],
["imgOption2", "DOM", "Nullam fringilla imperdiet eleifend"],
["imgOption3", "JavaScript", "Cras dapibus ipsum a consequat tincidunt"]
];
const output = imgContent[0].join(' ');
console.log(output);
You can use objects instead of nested arrays in that case:
const imgContent = [{ title: 'imgOption1', description: 'Lorem ipsum dolor sit amet.' }];
Then you can simply access the title/description using
imgContent[0].title // imgOption1
imgContent[0].description // Lorem ipsum dolor sit amet.

How to parse an HTML (or HTML in string) and read specific elements (H2) using JavaScript in ServiceNow?

I'm getting an HTML I need to parse it so that I can read text under a certain Heading. More specifically, there is a div tag that includes several H2 elements and I need to read only the text between the 3rd and 4th H2 heading, i.e. the Summary section.
<div>
<h2>Risks</h2>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
<p>Donec fermentum orci nec felis.</p>
<h2>Affected Systems</h2>
<p>Sed sollicitudin diam id sapien.</p>
<p>Ut libero.</p>
<h2>Summary</h2>
<!-- from here -->
<p>Vestibulum quam libero, malesuada et, ornare id, aliquet id, tellus.</p>
<p>Nullam dapibus viverra quam.</p>
<p>Vestibulum sit amet nunc vel justo dictum pharetra.</p>
<!-- through here -->
<h2>Avoidance</h2>
<p>Proin eleifend mi eget massa.</p>
<p>Pellentesque feugiat sapien a ante.</p>
</div>
Good question. You can use a recursive function well for that. The function gets the start point (third h2) and the end point (fourth h2). Then you iterate over every single element within these two points. I have now written the output to the console. But you can concatenate it into a string.
function getTextFromTo(rootNode, startNode, endNode) {
let pastStartNode = false, reachedEndNode = false, textNodes = [];
function getTextNodes(node) {
if (node == startNode) {
pastStartNode = true;
} else if (node == endNode) {
reachedEndNode = true;
} else if (node.nodeType == 3) {
if (pastStartNode && !reachedEndNode && !/^\s*$/.test(node.nodeValue)) {
textNodes.push(node);
}
} else {
for (var i = 0, len = node.childNodes.length; !reachedEndNode && i < len; ++i) {
getTextNodes(node.childNodes[i]);
}
}
}
getTextNodes(rootNode);
return textNodes;
}
const from = document.querySelector('div :nth-child(5)'); // from
const to = document.querySelector('div :nth-child(11)'); // to
const root = document.querySelector('div');
var textNodes = getTextFromTo(root, from, to);
for (let i = 0, len = textNodes.length, div; i < len; ++i) {
console.log(textNodes[i].data)
}
<div class="col-md-12">
<h2>title 1</h2>
<ul><li></li></ul>
<h2>title 2</h2>
<ul><li></li></ul>
<h2>Resume</h2>
<p>text 1</p>
<p>text 2</p>
<p>text 3 this one</p>
<p>text 4</p>
<p>text 5 this one</p>
<h2>next title</h2>
</div>
The originator of this cool function is #TimDown. I just adapted it. How can I find all text nodes between two element nodes with JavaScript/jQuery?
You can use regex for it
/(?<=<h2>Résumé<\/h2>)(.|\n)*?(?=<h2>)/g
This will get all the text after <h2>Résumé<\/h2>' till next <h2> tag.

How can I extract image id from an API in javascript?

So I have an app which uses Google Books API, and I have a div with image poster.
Thus i need to get image id from image url in Google API to change posters of books in these divs.
Javascript code:
const IMG_URL = "http://books.google.com/books/content?id="; //after "id=" I need to insert a particular image id
Function for showing books:
function showBooks(data){
data.forEach(book => {
const {title, authors, description} = book;
const bookEl = document.createElement('div');
bookEl.classList.add('book');
bookEl.innerHTML = `
<div class="border"></div>
<img src="${IMG_URL + }"> //here I should concatenate url with book id
<div class="book_info">
<h3>Book title</h3>
<p>Author</p>
</div>
<div class="overview">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris mi augue, ultricies vitae nisi vitae,
suscipit elementum risus. Suspendisse vitae porta tellus, a finibus lorem. </p>
</div>
`
});
}
What it looks like in the API:
"thumbnail": "http://books.google.com/books/content?id=WvfgAAAAMAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api"
I would construct a URL object and then extract the id parameter
const url = new URL(yourImageUrl)
const id = url.searchParams.get("id")
Read more about the URL class here: https://developer.mozilla.org/de/docs/Web/API/URL

Put text with line breaks in the editor and make it look good

I am a beginner in javascript and I have a problem and I do not know how to put text with many line breaks in addition to putting variables,I know that there is another way that is to put the text and the variables in a stright line but I would like another way,since I have a lot of text and I wish I could read it and modify it to my liking. :)
My question is how can I do this without having to make a straight line in the code?
I would like to have something like this in my code and being able to add variables to it
function procesDATA (LINKS, DATAINF, State, Callback) {
console.log(DATAINF);
console.log(LINKS);
var text = "Lorem ipsum"+ DATAINF.geo + "dolor sit amet, consectetur adipiscing elit."
"Sed hendrerit sapien sit amet mattis facilisis." `+ DATAINF.name +` "Donec dolor mi,
dapibus nec sollicitudin ut, pulvinar" "eu" "ex. Maecenas nec faucibus turpis. Vestibulum
ante erat.`+ DATAINF.date`";
fs.writeFile(DATAINF.gamename + ".txt", text,"utf-8", function(err) {
let OK = ["Archivo Guardado"]; console.log(OK);
});
}
Thank you very much to those who can help me :)
The new way
Using "Template literals", text will be verbatum in between the `tick` marks -- including new lines and leading tabs:
var text = `Lorem ipsum ${DATAINF.geo} dolor sit amet, consectetur adipiscing elit."
"Sed hendrerit sapien sit amet mattis facilisis." ${DATAINF.name} "Donec dolor mi,
dapibus nec sollicitudin ut, pulvinar" "eu" "ex. Maecenas nec faucibus turpis. Vestibulum
ante erat. ${DATAINF.date}`;
To integrate varibles wrap them with ${ varible in here }
The old way
While reliable, it's clunky has many caveat's... You have to understand how to wrap quotes and/or escape single/double quotes. (I chose to wrap with single quotes because the text contained many double quotes.)
var newline = "\n"; // if windows maybe use "\r\n"
var text = 'Lorem ipsum ' + DATAINF.geo + ' dolor sit amet, consectetur adipiscing elit. ' + newline;
text += 'Sed hendrerit sapien sit amet mattis facilisis. ' + DATAINF.name + ' Donec dolor mi, ' + newline;
text += 'dapibus nec sollicitudin ut, pulvinar" "eu" "ex. Maecenas nec faucibus turpis. Vestibulum ' + newline;
text += 'ante erat. ' + DATAINF.date + newline;
Wrap and/or escape quotes
NOTE: Only for the "old way"... you _don't_ have to deal with this if using the "new way"
You can use single quotes to wrap double quotes:
var foo = 'this has a double quote" in here';
Or you can use double quotes to wrap single quotes:
var foo = "this has a single quote' in here";
If you have both single and double quotes, you have to escape the one's that match the wrapper with a backslash:
// since we wrap with double, escape the inner double with a backslash
var foo = "this has \" both in ' here";
// since we wrap with single, escape the inner single with a backslash
var foo = 'this has " both in \' here';
Edit: Unless your question is just about how to format in the editor in which case
just do this.
"The question brown fox " + object.info +
"Jumped over " + object.otherinfo +
"The lazy " + object.extrainfo +
"dog"
i dont know why you have the extra ` in your ideal string.
unless you are talking about formatting the final output content in a file in which case you can just add
\n
where you want new lines.
For more information
var text = `Lorem ipsum ${DATAINF.geo} dolor sit amet, consectetur adipiscing elit.\n Sed hendrerit sapien sit amet mattis facilisis.\n ${DATAINF.name} Donec dolor mi, dapibus nec sollicitudin ut, pulvinar" "eu" "ex. Maecenas nec faucibus turpis. Vestibulum ante erat.\n ${DATAINF.date}`;

Adding View Details Button with JS

I'm trying to add a view details button to each product using JS. I want it to look for each instance of the class "clsItemBlock" and then append the html inside of clsItemPublished" The code below is adding multiple buttons on the first product, instead of one one each.
In a PERFECT world, since I know there are only 15 products per page, I could have it only check 15 times to prevent it from looping constantly.
MY JS:
var divs = document.getElementsByClassName('clsItemBlock');
for (var i = 0; i < divs.length; i++)
{
var iDiv = document.createElement('div');
iDiv.id = 'detail_button';
document.getElementsByClassName('clsItemPublished')[0].appendChild(iDiv);
iDiv.innerHTML = 'View Details';
}
FIDDLE:
http://jsfiddle.net/ptc6ws9o/1/
Or, if it is appropriate you can just use details and summary tags: http://jsfiddle.net/dorgLr71/
<details>
<summary>View Details</summary>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin
dapibus porttitor libero, eget rutrum nibh laoreet et.
Pellentesque porttitor erat ligula, id elementum est egestas
eget. Mauris gravida dui ut leo tempor, nec placerat tortor
hendrerit.
</p>
</details>
GOT IT!
var divs = document.getElementsByClassName('clsItemBlock');
for (var i = 0; i < divs.length; i++)
{
var iDiv = document.createElement('div');
iDiv.id = 'detail_button';
document.getElementsByClassName('clsItemPublished')[i].appendChild(iDiv);
iDiv.innerHTML = 'View Details';
}

Categories

Resources