How to get the id of all paragraph which are selected? - javascript

I am working with android webview and for achieving some functionality i need to integrate javascript. I am new to javascript to please tell me how to get the paragraphs id(id of each paragraph which are under selection). In more details:
Like i am having data-
<p id="01">hhh dhghdg
<span id="1.1">dada</span>
<span id="1.2">dgsdd</span>
</p>
<p id="02">dsdgs dhgd hdhd
<span id="2.1">dada</span>
<span id="2.2">dgsdd</span>
</p>
So you select some data i.e "hhh dhghdg dsdgs" so this data belongs to multiple paragraph p1 and p2 so i want to get the id of both the paragraph using javascript.
Please tell me how to get this.

PPK has a very detailed post:
http://www.quirksmode.org/dom/range_intro.html
Which describes range objects. I've not done this before but by the looks of things you'll need to use:
window.getSelection()
Which should return a selection object from which you can get a range object which will contain all the selected elements (as described in the link above)
From scanning the docs on MDN:
https://developer.mozilla.org/en-US/docs/DOM/window.getSelection
You'll get an HTML string back from which you could attempt to get all the ids from, using a regular expression, something like this:
var underSelection = window.getSelection().getRangeAt(0);
var idsRegEx = /#\s(id|class)="[^"]+"/;
var idMatches = idsRegEx.match(underSelection);
//then clean and do something with the ids
I haven't tested any of this but I'm hoping it gets you started.
EDIT: additional info
If you're using jQuery you might be able to load the selection into a jQuery object and get all the ids out by doing :
var IDs = [];
$(underSelection).find("p").each(function(){ IDs.push(this.id); });

You have to use either
document.documentElement.id
or
document.getElementsByTagName('HTML')[0].id

Related

Parsing part of a html text using javascript

The output on my page after generating a certain link is:
<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">
SUCCESS|78502|25cca4bc-08f9-4a59-85f8-64e0d0700924|
</string>
What i'm interested in is the 78502 because it's an unique id i need to use in later protractor tests.
This is the html part of it.
<span xmlns="http://www.w3.org/1999/xhtml" class="text">SUCCESS|78502|25cca4bc-08f9-4a59-85f8-64e0d0700924|</span>
I'm prety blocked atm since i've never done something like this, the first step i took was getting the xpath of the html element and applying the getText method on it and console.log-ing it to check that i can at least get the value but that doesn't seem to give me the value of the element.
Any materials/links that can help me better understand what i need to do is appreciated!
Is that html element unique? If there isn't any other with same xmlns attribute and same class you can get that with pure Javascript:
// Get text inside the element
var text = document.querySelector('span.text[xmlns="http://www.w3.org/1999/xhtml"]').innerText;
// Get an array of the parts ["SUCCESS", "78502" ...]
var text_parts = text.split('|');
console.log(text_parts);
// If that array has a second element (that id) get that second element
var id = '';
if (text_parts.length >= 2) id = text_parts[1];
console.log(id);
If there's a way to generate that html with an id so it's unique it would be more safe, so you are sure the querySelector will pick the right one.
So if you have
<span id="span-with-id" xmlns="http://www.w3.org/1999/xhtml" class="text">SUCCESS|78502|25cca4bc-08f9-4a59-85f8-64e0d0700924|</span>
you could use
var text = document.querySelector('#span-with-id').innerText;
Note that you have to do that with Javascript, after this HTML element is inserted into the document.

How do I iterate an output data from an array in an object

I am trying to create a daily weather app and i'm having issues trying to figure out how to output the data into cards for all seven days. its currently only outputting the last day. I know that its because if am setting it to $("#card__days").html( but im not sure how to add onto the current html.
Is there also any easier way to output this information? I feel like I did way too much for a simple task. Thank you
function updateDaily(data) {
Object.keys(data.daily.data).forEach(function (i) {
// call to find what the day is.
let date = calculateDay(data.daily.data[i].time);
console.log(data.daily.data[i]);
let iteration = i;
let high = data.daily.data[i].temperatureHigh;
let low = data.daily.data[i].temperatureLow;
let feels = data.daily.data[i].apparentTemperature;
let desc = data.daily.data[i].summary;
let icon = data.daily.data[i].icon;
let skycons = new Skycons({ color: "#3e606f" });
$("#card__days").html(`
<div class="card__daily">
<h2 id="daily__date"${iteration}">${date}</h2>
<canvas src="" alt="icon" class="icon" id="daily__icon${iteration}"></canvas>
<div class="degrees">
<h3 id="daily__high${iteration}" class="temp">${high}℉ / ${low}℉</h3>
</div>
<h3 id="daily__desc${iteration}">${desc}</h3>
</div>
`);
skycons.add(
document.getElementById("daily__icon" + i),
icon
);
skycons.play();
});
}
EDIT: Here is what it currently looks like and some data from the API.
Current Visual Output
Some data from Object
If you want to make all seven cards appear, use .append() instead:
$("#card_days").append(/* Your card HTML */);
You only see the last card because in each iteration the for loop overwrites the html with the latest ${iteration} data, instead of creating a new piece of data and a new html element. To fix this:
You could use the $("#card_days").append method, from the other comment in this thread, but personally in a similar situation I used:
$("#card_days").insertAdjacentHTML('beforeend', html) method, it will insert the code you give it as an html parameter just before the closing tag of the element you selected.
As a side note, I only used insertAdjacentHTML because I needed the user to be able to create and delete these html elements, so their amount could not be predefined. In your case, it seems like you know you need exactly 7 elements. If this is the case, I would suggest to stick with html and css, and the only usage of JS would be to update a placeholder text with the newly-fetched data. Hard-coding in this case seems a bit more error-proof :)

Creating dynamic divs

Trying to make a dynamic div but i don't know how. Wrote a solidity smart contract that accepts an array of struct. In the smart contract i can use a get function to display the data inside. Data in the array is treated like a history, it consists of amount (making a crowdfund site), date, currency used, etc. Since the get function in the smart contract can only extract one part of the array, i thought of putting the get function into the while loop and extract the whole history array..
<div id=set>
<a>value1</a>
<a>value2</a>
</div>
I'm trying to dynamically create another div with the same amount of < a > in the div. If i had 10 sets of data to display in that div, i wish to create only 10 sets of that div. Can createElement() be used to do that? Couldn't find any solution that works. Totally have no idea on how to create it. Can someone please help.
Would it be rational to extract the data from the array using a while loop and putting it in a div to display or would it use too much gas for this to work?
I don't get why would you want to do this, but you can do like this:
$('#set a').each(function(){
$('#set').after( "<div></div>");
});
It selects all of the <a>...</a> inside the <div id="set">...</div> element, and for each one of those inserts a <div></div> element. It inserts the element right next to #set but you can change that to any other element you could select.
I'm supplying jQuery code since you tagged the question as jQuery.
Hope it helps,
You can get the number of anchor tags by using this function getElementsByTagName('a').length from the hosting div. Then use that number to create new divs. This solution is done using vanilla JS.
function createDynamicDivs(){
var newDiv = document.createElement("div");
var noOfAnchors = document.getElementById('set').getElementsByTagName('a').length;
for(var i=0;i<noOfAnchors;i++){
var newContent = document.createElement("a");
newContent.textContent= "Test ";
newDiv.appendChild(newContent);
}
document.getElementById('new').appendChild(newDiv);
}
<div id=set>
<a>value1</a>
<a>value2</a>
</div>
<div id="new"></div>
<button onclick="createDynamicDivs()">Generate</button>

jQuery how to do the following

I've the following question, let say we have a div like this:
These are dynamically formatted divs, with the classes 'row', 'element' and 'isotope-item' are always present. Everything in between can vary per div.
What I want is to the following:
As you see the commmas are no longer there and seperate classes between the commas are now one class.
Anyone any idea?
I already have the following to remove the commas:
$('div.element').each(function () {
var _sCurrClasses = jQuery(this).attr('class');
jQuery(this).attr('class', _sCurrClasses.replace(/,/g, ' '));
});
I would advise doing this backend,but in JavaScript you could:
This will not account for the space in the words though.
You would need to pass then trough separately one by one and replace.
or store them in a data-attribute and format when you need them.
<string>
var classesFormat = classes.replace(/,/g, '');
var classesList = classesFormat.split(" ");
for(String c : classesList)
{
$("#id").addClass(c);
}
</string>
So you could create a data-attribute for each one instead.
Go through each one, format and the add to class.
<div data-id="Microsoft Office," class="test test test">
With the script
$(this).attr("data-id") // will return the string "Microsoft Office,"
or .data() (if you use newer jQuery >= 1.4.3)
$(this).data("id") // will return the Microsoft Office,
And then do your replace after that and addClass.
I don't think classes work like you think they do
the first PICTURE you posted would result in that div having the follwing classes
row
element
Microsoft
Office,
My
SQL,
Page
Rank
isotope-item
Note the , is PART of the class
You want, according to the second PICTURE
row
element
MicrosoftOffice
MySQL
Page
Rank
isotope-item
Removing , is just as you posted ... the problem is, how do you determine which spaces to remove, and which to keep?
(I posted this as an ANSWER, but I KNOW IT IS NOT AN ANSWER)

Grab a single digit out of a big mess of html

I am grabbing a div from the document with :
var myTotal = window.document.getElementById('status').innerHTML;
which returns a big mess of HTML
<div id="foo">
<a href="bar" onclick='_gaq.push(["_trackEvent", "The", "Total",])'>
<img src="foo.gif" alt="foo" height="22px;/" width="15px;"></a>
</div>
<a href="bar" onclick='_gaq.push(["_trackEvent", "The", "Total",])'>
MY TOTAL:
<span style="font-size: 12px; color: #F3A428; font-weight:normal;"> 8 item(s) </span>
</a>
Can one of you expression wizards please show me how I can grab just the number in the span, in this example an 8 ?
Can you give the span an id and reference it directly?
If not, then this regex should return the number in the span: /<span[^>]+>\s*(\d+)/
I'm assuming that there is only ever one span in the div.
This should help you
var myTotal = window.document.getElementById('status').getElementsByTagName('span')[0].innerHTML
myTotal = myTotal.replace(/(^\d+)(.+$)/i,'$1');
In jQuery, without even getting the inner HTML it would be this:
var items = $("#status span").first().text();
items = parseInt(items, 10);
alert(items); // 8
If you control the HTML, it would be advisable to put a unique ID on the span containing the result and then it's easier to retrieve and not dependent upon the structure around it or better yet, have it output into the page as a JS variable that you can just directly read and not have to deal with the presentation.
Seen in a jsFiddle here: http://jsfiddle.net/jfriend00/UqcxS/
You can also try, just using innerText
window.document.getElementById('status').innerText.replace(/[^0-9]/gi, '');
http://jsfiddle.net/X9ffE/
Use jQuery instead, it has a lot of functions that can help you find specific elements in your page. Also, you may want to add identification for your elements like class and id.

Categories

Resources