Using TTTAttributedLabel to format html code in UILabel - html

I'm using TTTAttributedLabel to show HTML code in UILabel that contains code (like bold, italic etc) and links.
This is my code
- (void)fetchText
{
NSMutableAttributedString * tmp = [[NSMutableAttributedString alloc] initWithData:self.genericInfo.getLocalizedDescription.toData
options:#{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute:#(NSUTF8StringEncoding)}
documentAttributes:nil
error:nil];
[self.labelText setText:tmp afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
[mutableAttributedString addAttribute:NSFontAttributeName value:FONT_REGULAR(18.0f) range:NSMakeRange(0, tmp.length)];
return mutableAttributedString;
}];
}
The problem is I can't see any HTML bold or italic, but I can see only links.
There is a problem with my code or is a bug of TTTAttributedLabel?
Here the HTML contained in genericInfo.getLocalizedDescription
<p><strong>By subway</strong><br />
Take the Red line and get off at Rho Fiera Milano Expo stop.<br />
web: atm-mi.it<br />
download: underground map</p>
<p> </p>
<p><strong>By car</strong><br />
From the motorways A7-Genoa, A1 Bologna and A4-Turin take ring road west (tangenziale ovest) and go to fieramilano exit.<br />
From the A4-Venice motorway take the Pero-fieramilano exit.<br />
From the motorways A8-Varese and A9-Como at the Milano nord junction take the A4-Venice and go to fieramilano exit.<br />
From Milan follow the road signs to the motorways A8 Varese or A4 Turin and take the fieramilano exit.</p>
<p><strong>AREA C</strong><br />
Restrictive regulations will be imposed on cars entering downtown Milan (Area C - limited traffic area (Ztl).</p>
<p>web: areac.it</p>
<p><strong>By taxi</strong><br />
It is possible to reserve a taxi by calling one of the the following numbers:<br />
+39 02.8585 +39 02.6969 +39 02.4040 +39 02.4000 +39 02.5353</p>
<p><strong>By train</strong><br />
Milan exhibition venue is reachable by railway Passante, suburban lines S5 (Varese-Varese-Milano Passante-Treviglio) and S6 (Novara-Milano Passante -Treviglio); S5 and S6 stop directly in Rho Fiera Milano Expo Station.<br />
S5 and S6 lines are accessible from the heart of Milan in the following stations: Certosa, Villapizzone, Lancetti, Porta Garibaldi sotterranea, Repubblica, Porta Venezia, Dateo and Porta Vittoria.<br />
Further information, timetable and tickets purchasing: trenord.it/it/in-fiera.aspx<br />
Several inter-regional trains on the Turin-Novara-Milan line stop at the Rho Fiera Milano Expo station.<br />
A shuttle service connects the trains stations Rho and Rho Fiera Milano Expo.</p>
<p><strong>By plane</strong></p>
<p><em>From LINATE Airport</em><br />
Bus 73 and X73; get off in Piazza San Babila and take the subway, Red line, to Rho Fiera Milano Expo.<br />
During the exhibition days a bus transfer from/to Linate Airport is available:<br />
- departing from the airport, domestic arrivals area, from 8:30 to 13:30 and from 15:00 to 18:00, every hour.<br />
- departing from fieramilano, East Gate bus parking area, from 9:30 to 12:30 and from 14:00 to 19:00, every hour.</p>
<p><em>From MALPENSA Airport</em><br />
Take Malpensa Express train (Terminal 1 railway station) , directed to Milano Centrale Station – alight at Milano Porta Garibaldi and take Suburban railway lines S5 or S6 (13 minutes journey )<br />
Take Malpensa Express train (Terminal 1 railway station) , directed to Milano Cadorna Station (29 minutes journey on non stop trains). From there take the subway, Red line, to Rho Fiera Milano Expo.</p>
<p>Further information, timetable and tickets purchasing: www.trenord.it or www.malpensaexpress.it/</p>
<p><em>From ORIO AL SERIO Airport</em><br />
Direct bus transportation available only during events:<br />
- Orio Shuttle (€ 12.00/one way - € 20.00 round trip): departures from the airport, Arrival area, bus shelter 1, at 8:45, 9:15 and 10:30. Departures from Fiera Milano, East gate bus parking area, at 15:30, 16:30 and 18:00.</p>
<p>web: www.orioshuttle.com</p>
<p>Orio bus Express (€ 11.50/one way - € 19.50 round trip):<br />
departures from the airport, Arrivals, bus shelter 3/4, at: 8:30, 10:15 and 11:00. Departures from Fiera Milano at 15:15, 16:00 and 18:00 from East Gate bus parking area.</p>
<p>web: autostradale.it</p>

Edit: I think it's not automatic the bold and italic detection, you should add an attribute with the range of what you want bold and italic for example:
NSDictionary *attrs = #{ NSFontAttributeName: [UIFont LNHelveticaNeueLightOfSize:15 + [Menu prefLectura]],
NSForegroundColorAttributeName: [UIColor darkTextColor] };
NSDictionary *subAttrsMedium = #{
NSFontAttributeName:[UIFont LNHelveticaNeueMediumOfSize:15 + [Menu prefLectura]],
NSForegroundColorAttributeName:[UIColor blackColor] };
NSMutableAttributedString* attrString = [[NSMutableAttributedString alloc] initWithString:cell.contenido.text attributes:attrs];
NSRange range = [cell.contenido.text rangeOfString:[NSString stringWithFormat:#"%#",item[#"text"]]];
[attrString addAttributes:subAttrsMedium range:range];
I don't know if this could be a solution for you but it's the only way I could make it work
Using TTTAttributedLabel I've discovered that this has to be the order:
Create Attributed String like you want it to be (no changes to it after second step)
setText to label
(optional) add links detection
So, you should invert these 2 lines:
[mutableAttributedString addAttribute:NSFontAttributeName value:FONT_REGULAR(18.0f) range:NSMakeRange(0, tmp.length)];
[self.labelText setText:tmp afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
Hope it helps

Related

How I can loop into api-pltform json data using vue axios

{
"#context":"\/contexts\/Movie",
"#id":"\/movies",
"#type":"hydra:Collection",
"hydra:member":[
[
{
"id":"001db4b9-7042-11e9-b3a6-0ac98b070556",
"title":"Kalank",
"originalTitle":"कलंक",
"originalLanguage":"",
"description":"Kalank is an Indian Hindi-language period drama film directed by Abhishek Varman and produced by Karan Johar, Sajid Nadiadwala and Fox Star Studios.\n\nCinema: Cineco City Center\nMovie Timings: 5.00 + 8.15 + 11.30 PM.\n",
"releasedAt":"2019-04-17T00:00:00+00:00",
"imdbId":"tt6988116",
"posterUrl":null,
"genre":"Drama",
"cinemaName":"Cir"
},
{
"id":"00bfc9b3-7042-11e9-b3a6-0ac98b070556",
"title":"Stockholm",
"originalTitle":"Stockholm",
"originalLanguage":"",
"description":"Based on the absurd but true 1973 bank heist and hostage crisis in Stockholm that was documented in the New Yorker as the origins of the ‘Stockholm Syndrome’.\n\nCinema: Cineco Seef II\nMovie Timings: 7.00 + 9.00 + 11.00 PM.\n",
"releasedAt":"2019-04-12T00:00:00+00:00",
"imdbId":"tt6474040",
"posterUrl":"\/ko3AS33BLNEBcp1CO4FvdRltTxr.jpg",
"genre":"Drama",
"cinemaName":"SeI"
},
{
"id":"0181072c-7042-11e9-b3a6-0ac98b070556",
"title":"Shazam!",
"originalTitle":"Shazam!",
"originalLanguage":"",
"description":"We all have a superhero inside us, it just takes a bit of magic to bring it out. In Billy Batson’s case, by shouting out one word – SHAZAM! – this streetwise fourteen-year-old foster kid can turn into the adult superhero Shazam.\n\nCinema: Cineco City ",
"releasedAt":"2019-03-23T00:00:00+00:00",
"imdbId":"tt0448115",
"posterUrl":"\/xnopI5Xtky18MPhK40cZAGAOVeV.jpg",
"genre":"Action",
"cinemaName":"Center"
},
{
"id":"06b71b0a-6de5-11e9-962d-0adc8ab87612",
"title":"Escape Room",
"originalTitle":"Escape Room",
"originalLanguage":"",
"description":"Six strangers find themselves in a maze of deadly mystery rooms, and must use their wits to survive.\n\nCinema: Cineco City Center\nMovie Timings: 10.30 AM. + 12.30 + 2.30 + 4.30 + 6.30 + 8.30 + 10.30 PM.\n",
"releasedAt":"2019-01-03T00:00:00+00:00",
"imdbId":"tt5886046",
"posterUrl":"\/15AlGTlaZa3W2zmIL4ehnCh8Xe0.jpg",
"genre":"Action",
"cinemaName":"Center"
}
}],
{
"page":1,
"pageSize":25,
"pageCount":8,
"totalHits":176
}
],
"hydra:totalItems":2
}
I have an api-platform data source in a JSON format as shown above. However, I would like to print each record in vue js app in a ..
I tried the following and doesn't work:
<ul>
<li v-for="movie in movies">
{{ movie['hydra:member'][0][0].title}}
</li>
<li v-for="movie in movies">
{{ movie['hydra:member'][0][0].genre}}
</li>
</ul>
</div>
Any help how to loop in api-platform JSON data using Vue axion ?! I need the correct for loop to print the data available in movie['hydra:member'][0][0].objects
You can try
<ul>
<li v-for="movie in movies['hydra:member']">
{{ movie[0].title}}
{{ movie[0].genre}}
</li>
</ul>

Trying to get property 'addressLine1' of non-object in Laravel

hello guys i have been trying to access the value through multidimensional array in laravel view
my json array is
{
"results":[
{
"id":4582,
"name":"Rocklands Bouldering Permit",
"description":"This permit guarantees entry to all bouldering areas in Rocklands for the validity duration, including CapeNature, de Pakhuys and Travellers Rest<br><u><strong>All climbers visiting Rocklands must be in possession of this permit to climb on any land and must carry this permit with them at all times </strong></u>.<br><br><strong>Booking Terms and Conditions:</strong><br>The following Terms and Conditions apply to all bookings (walk-in or pre-paid):<br><br>Damage / loss / death<br><br>It is a distinct condition of admission to any protected area, that the Western Cape Nature Conservation Board and the property owners accept no responsibility or liability arising from a visit(s) <br><br>howsoever caused:<ul><li>For any death, injury or illness sustained or suffered by any person.</li><li>For theft/loss/damage to any property, whether allegedly due to the negligence of the board/</li><li>officers/employees/agents or arising from the use of any facilities supplied/made available.</li><li>CapeNature and the landowners accepts NO responsibility for clothing or any items left behind at our facilities.</li><li>From any alleged defect in any utensil/equipment/services/vessel/vehicle.</li><li>From any other conveyance supplied/made available, or from any liquid/food supplied.</li><li>From any other matter arising, in any other manner and from any other cause whatsoever.</li></ul><br><strong>Breaking of the rules</strong><br>CapeNature and the landowners reserves the right to deny access or to evict guests who do not adhere to the rules and regulations of the CapeNature and landowners and/or its reserves. Money paid for these bookings will be forfeited.<br><br><em><strong>These rules include, but are not limited to the following:</strong></em><ul><li>Visitors are to have their bouldering permit with them upon entrance to the reserve.</li><li>No pets allowed on reserves, the only exception will be guide dogs for the blind.</li><li>No collection of bait, removing, damaging or disturbing of fauna or flora</li><li>Rowdy or unwanted behavior</li><li>All tariffs are subject to change without notification.</li><li>Stick to the marked walking trails</li><li>No puff or resin allowed</li><li>Carry out what you carry in</li></ul>",
"url":"https://www.quicket.co.za/events/4582-rocklands-bouldering-permit/",
"imageUrl":"//quicket.azureedge.net/media/0004303_360_360.Png",
"dateCreated":"2014-03-12T16:59:47.467",
"lastModified":"2018-05-31T10:27:35.4102002",
"startDate":"2014-03-13T10:24:00",
"endDate":"2024-03-01T10:24:00",
"venue":{
"id":0,
"name":"Rocklands",
"addressLine1":"",
"addressLine2":"",
"latitude":-32.1786111,
"longitude":18.8911111
},
{
"id":2830,
"name":"ROX TEST EVENT",
"description":"<span style=\"line-height: 20.7999992370605px;\">Description of the event will go here</span><br /><br /><span style=\"line-height: 20.7999992370605px;\">And you can add pictures or even a youtube video or two here! You can also add a <a target=\"_blank\" href=\"http://www.rockingthedaisies.com\">hyperlink</a></span><br /><br /><br /><iframe width=\"640\" height=\"360\" src=\"https://www.youtube.com/embed/soyeZp_3qN4\" frameborder=\"0\" allowfullscreen=\"\"></iframe>",
"url":"https://www.quicket.co.za/events/2830-rox-test-event/",
"imageUrl":"//quicket.azureedge.net/media/0007888_360_360.Jpeg",
"dateCreated":"2013-09-11T13:14:01.283",
"lastModified":"2018-06-05T10:29:28.574536",
"startDate":"2015-05-07T15:17:00",
"endDate":"2024-05-14T00:00:00",
"venue":{
"id":0,
"name":"Roxys cafe ",
"addressLine1":"14 Wandel Street",
"addressLine2":"",
"latitude":-33.931801,
"longitude":18.417017999999985
}
]
i wanted to get the value of "name" inside results array which i am able to get in my blade view but when i am trying to access "addressLine1" and "addressLine2" from my blade i am unable to get that and i can't for the life of me figure out what is wrong with my code.
following is my code in blade
#foreach($datas as $data=>$key)
#for($i=0;$i<2;$i++)
<h1>{{$datas[$data][$i]['name']}}</h1>
#endfor
#if(is_array($key))
#foreach($key as $k=>$v)
#if(is_array($v))
#foreach($v as $venue=>$place)
{{dd($place['venue']->addressLine1)}}
#endforeach
#endif
#endforeach
#endif
#endforeach
and this is the error i am getting
Trying to get property 'addressLine1' of non-object
Please help me out here Thanks in advance
P.S $datas is my json encoded array from controller
Your json has syntax error. If this is the json you pass to the blade, it may be the problem. What is the controller code?
Alright guys i solved the error but now foreach is repeating the same result 10 times for no reason at all how do i stop that?
here is my edited code in blade
#foreach($datas as $data=>$key)
#for($i=0;$i<10;$i++)
<h1>{{$datas[$data][$i]['name']}}</h1>
#endfor
#if(is_array($key))
#foreach($key as $k=>$v)
#foreach($v as $venue=>$place)
<h1>{{$v['venue']['addressLine1']}}</h1>
<h1>{{$v['venue']['addressLine2']}}</h1>
#endforeach
#endforeach
#endif
#endforeach
and here is my output
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
14 Wandel Street
Your second foreach have no use, try this one instead:
#foreach($datas as $data=>$key)
#for($i=0;$i<10;$i++)
<h1>{{$datas[$data][$i]['name']}}</h1>
#endfor
#if(is_array($key))
#foreach($key as $v)
<h1>{{$v['venue']['addressLine1']}}</h1>
<h1>{{$v['venue']['addressLine2']}}</h1>
#endforeach
#endif
#endforeach
Another improvement is to use the word key when the variable is a key from an array and not when is the value. And the for can be replaced too. Like this:
#foreach($datas as $data)
<h1>{{ $data['name'] }}</h1>
#if(is_array($key))
#foreach($key as $v)
<h1>{{ $v['venue']['addressLine1'] }}</h1>
<h1>{{ $v['venue']['addressLine2'] }}</h1>
#endforeach
#endif
#endforeach

HTML BUTTON WITH TEXT AND IMAGE

I am in a beginner programming class. We are only on chapter 4, so please keep that in mind. This class is using HTML with some javascript, we haven't really gotten too deep into javascript yet. My project for this week is to create two buttons, and when each one of these buttons are clicked a photo and a paragraph comes up. I have the button with the paragraph coming up but I can't figure out how to add the image. Everything I have found on the internet is super javascript, stuff I haven't learned. Here is my code, I just picked a random topic, haha
<!doctype html>
<!--Web page that displays quotes at the click of a button click. -->
<!--============================================================= -->
<html>
<head>
<title>Project2</title>
</head>
<body>
<div style="text-align:center">
<p>
<h2> <span style="color:red">Favorite Animals</span> </h2>
</p>
<input type="button" value="Slow Loris" onmouseover="this.style.backgroundColor='red';" onmouseout="this.style.backgroundColor='white';" onclick="document.getElementById('outputDiv').innerHTML=
'This animal might look like a harmless, big-eyed baby ewok, but ' +
'the slow loris is one of the only venomous mammals in the world. ' +
'Its subtle nature makes it popular in the illegal pet trade, but this ' +
'furry creature also carries a toxin that is released from the brachial ' +
'gland on the sides of its elbows. If threatened, the loris can take ' +
'the toxin into its mouth and mix it with saliva. The animal may also ' +
'lick or rub its hair with this mixture to deter predators from attack. ' +
'The toxin can cause death by anaphylactic shock in some people.';">
<input type="button" value="Sloth" onmouseover="this.style.backgroundColor='red';" onmouseout="this.style.backgroundColor='white';" onclick="document.getElementById('outputDiv').innerHTML=
'Sloths—the sluggish tree-dwellers of Central and South America—spend ' +
'their lives in the tropical rain forests. They move through the canopy ' +
'at a rate of about 40 yards per day, munching on leaves, twigs and buds. ' +
'Sloths have an exceptionally low metabolic rate and spend 15 to 20 hours ' +
'per day sleeping. And surprisingly enough, the long-armed animals are ' +
'excellent swimmers. They occasionally drop from their treetop perches ' +
'into water for a paddle.';">
</div>
<div id="outputDiv"></div>
</body>
</html>
simple just put the image inside, see jsfiddle
<input type="button" value="Slow Loris"
onmouseover="this.style.backgroundColor='red';"
onmouseout="this.style.backgroundColor='white';"
onclick="document.getElementById('outputDiv').innerHTML=
'<img src=https://www.thepharmaletter.com/media/image/actavis-logo-small.jpg>' +
'This animal might look like a harmless, big-eyed baby ewok, but ' +
'the slow loris is one of the only venomous mammals in the world. ' +
'Its subtle nature makes it popular in the illegal pet trade, but this ' +
'furry creature also carries a toxin that is released from the brachial ' +
'gland on the sides of its elbows. If threatened, the loris can take ' +
'the toxin into its mouth and mix it with saliva. The animal may also ' +
'lick or rub its hair with this mixture to deter predators from attack. ' +
'The toxin can cause death by anaphylactic shock in some people.';">
https://jsfiddle.net/bxcz3f8g/
As the property name suggests, innerHTML can be a full blown HTML content and not just text. You can put any valid HTML in that. And as per good practices, you should write those operations in a separate js file and import it.
function addContent(event) {
document.getElementById('outputDiv').innerHTML =
'<img width="80" src="https://i.ytimg.com/vi/n7gcats5uCQ/maxresdefault.jpg"/><br/><p>Sloths—the sluggish tree-dwellers of Central and South America—spend ' +
'their lives in the tropical rain forests. They move through the canopy ' +
'at a rate of about 40 yards per day, munching on leaves, twigs and buds. ' +
'Sloths have an exceptionally low metabolic rate and spend 15 to 20 hours ' +
'per day sleeping. And surprisingly enough, the long-armed animals are ' +
'excellent swimmers. They occasionally drop from their treetop perches ' +
'into water for a paddle.</p>'
}
<button onClick="addContent()">Sloth</button>
<div id="outputDiv" />
You could use the 'style' property of <img> to achieve what you are looking for. Within the style property you could set display:none, to hide the <img>. To make it visible again, just change display back to display:inline when a button gets clicked. Try the following:
<!doctype html>
<!--Web page that displays quotes at the click of a button click. -->
<!--============================================================= -->
<html>
<head>
<title>Project2</title>
</head>
<body>
<div style="text-align:center">
<p>
<h2> <span style="color:red">Favorite Animals</span> </h2>
<img id='slow' src='slowLoris.jpg' alt='Slow Loris' style='width:200px;height:150px;display:none;'>
<img id='sloth' src='sloth.jpg' alt='Sloth' style='width:200px;height:150px;display:none;'>
</p>
<input type="button" value="Slow Loris"
onmouseover="this.style.backgroundColor='red';"
onmouseout="this.style.backgroundColor='white';"
onclick="
document.getElementById('sloth').style='width:200px;height:150px;display:none;'
document.getElementById('slow').style='width:200px;height:150px;display:inline;'
document.getElementById('outputDiv').innerHTML=
'This animal might look like a harmless, big-eyed baby ewok, but ' +
'the slow loris is one of the only venomous mammals in the world. ' +
'Its subtle nature makes it popular in the illegal pet trade, but this ' +
'furry creature also carries a toxin that is released from the brachial ' +
'gland on the sides of its elbows. If threatened, the loris can take ' +
'the toxin into its mouth and mix it with saliva. The animal may also ' +
'lick or rub its hair with this mixture to deter predators from attack. ' +
'The toxin can cause death by anaphylactic shock in some people.';">
<input type="button" value="Sloth"
onmouseover="this.style.backgroundColor='red';"
onmouseout="this.style.backgroundColor='white';"
onclick="
document.getElementById('slow').style='width:200px;height:150px;display:none';
document.getElementById('sloth').style='width:200px;height:150px;display:inline;'
document.getElementById('outputDiv').innerHTML=
'Sloths—the sluggish tree-dwellers of Central and South America—spend ' +
'their lives in the tropical rain forests. They move through the canopy ' +
'at a rate of about 40 yards per day, munching on leaves, twigs and buds. ' +
'Sloths have an exceptionally low metabolic rate and spend 15 to 20 hours ' +
'per day sleeping. And surprisingly enough, the long-armed animals are ' +
'excellent swimmers. They occasionally drop from their treetop perches ' +
'into water for a paddle.'">
</div>
<div id="outputDiv"></div>
</body>
</html>
Edit
If you don't mind changing your code a bit, a cleaner solution would be:
<!doctype html>
<!--Web page that displays quotes at the click of a button click. -->
<!--============================================================= -->
<html>
<head>
<title>Project2</title>
</head>
<body style='text-align:center'>
<h2> <span style="color:red">Favorite Animals</span> </h2>
<div id='slow' style='text-align:center;display:none'>
<img src='slowLoris.jpg' alt='Slow Loris'>
<p>This animal might look like a harmless, big-eyed baby ewok, but
the slow loris is one of the only venomous mammals in the world.
Its subtle nature makes it popular in the illegal pet trade, but this
furry creature also carries a toxin that is released from the brachial
gland on the sides of its elbows. If threatened, the loris can take
the toxin into its mouth and mix it with saliva. The animal may also
lick or rub its hair with this mixture to deter predators from attack.
The toxin can cause death by anaphylactic shock in some people.</p>
</div>
<div id='sloth' style='text-align:center;display:none'>
<img src='sloth.jpg' alt='Sloth'>
<p> Sloths—the sluggish tree-dwellers of Central and South America—spend
their lives in the tropical rain forests. They move through the canopy
at a rate of about 40 yards per day, munching on leaves, twigs and buds.
sloths have an exceptionally low metabolic rate and spend 15 to 20 hours
per day sleeping. And surprisingly enough, the long-armed animals are
excellent swimmers. They occasionally drop from their treetop perches
into water for a paddle.</p>
</div>
<input type="button" value="Slow Loris"
onmouseover="this.style.backgroundColor='red';"
onmouseout="this.style.backgroundColor='white';"
onclick="
document.getElementById('slow').style='text-align:center;display:inline';
document.getElementById('sloth').style='text-align:center;display:none'">
<input type="button" value="Sloth"
onmouseover="this.style.backgroundColor='red';"
onmouseout="this.style.backgroundColor='white';"
onclick="
document.getElementById('sloth').style='text-align:center;display:inline';
document.getElementById('slow').style='text-align:center;display:none'">
</div>
</body>
</html>
You need to use image tag <img> to insert images, e.g.
<img src="https://www.internationalanimalrescue.org/sites/default/files/sumatran_slow_loris.jpg">
Here the value of src points to the source of the image. You can use one from your computer too (just specify its relative path from your html file).
A few other points. You can use <button> to create button. <input> is to create user input fields. And it's better to separate your HTMl from your Javascript code and then just toggle its display property with your code (you can also move these code to a separate place from your button creation, if you've already learned it).
<div style="text-align:center">
<p>
<h2> <span style="color:red">Favorite Animals</span> </h2>
</p>
<button type="button"
onmouseover="this.style.backgroundColor='red';"
onmouseout="this.style.backgroundColor='white';"
onclick="document.getElementById('outputDiv1').style.display = 'block'; document.getElementById('outputDiv2').style.display = 'none'">Slow Loris</button>
<button type="button"
onmouseover="this.style.backgroundColor='red';"
onmouseout="this.style.backgroundColor='white';"
onclick="document.getElementById('outputDiv2').style.display = 'block';
document.getElementById('outputDiv1').style.display = 'none'"> Sloth</button>
</div>
<div id="outputDiv1" style="display:none">slow loris<img src="https://www.internationalanimalrescue.org/sites/default/files/sumatran_slow_loris.jpg" alt="loris" height="100" width="140"></div>
<div id="outputDiv2" style="display:none">sloth<img src="http://kids.nationalgeographic.com/content/dam/kids/photos/animals/Mammals/Q-Z/sloth-beach-upside-down.adapt.945.1.jpg" alt="sloth" height="100" width="140"></div>

Parsing HTML with HTML::TreeBuilder::XPath

I have many HTML documents that I need to parse. Here's an example of the data so that I can explain myself a little better
<div id="filerDiv">
<div class="mailer">Mailing Address
<span class="mailerAddress">65 MARKET STREET, SUITE 1207,</span>
<span class="mailerAddress">CAMANA BAY, P.O. BOX 31110</span>
<span class="mailerAddress">GRAND CAYMAN E9 KY1-1205</span>
</div>
<div class="mailer">Business Address
<span class="mailerAddress">65 MARKET STREET, SUITE 1207,</span>
<span class="mailerAddress">CAMANA BAY, P.O. BOX 31110</span>
<span class="mailerAddress">GRAND CAYMAN E9 KY1-1205</span>
<span class="mailerAddress">345 943 4573</span>
</div>
<div class="companyInfo">
<span class="companyName">GREENLIGHT CAPITAL RE, LTD. (Filer)
<acronym title="Central Index Key">CIK</acronym>: 0001385613 (see all company filings)</span>
<p class="identInfo"><acronym title="Internal Revenue Service Number">IRS No.</acronym>: <strong>000000000</strong><br />Type: <strong>10-Q</strong> | Act: <strong>34</strong> | File No.: <strong>001-33493</strong> | Film No.: <strong>161612131</strong><br /><acronym title="Standard Industrial Code">SIC</acronym>: <b>6331</b> Fire, Marine & Casualty Insurance<br />Assistant Director 1</p>
</div>
</div>
I need to grab the four span elements which follow the second div element with the class mailer. Here is the code I have so far
my $root = HTML::TreeBuilder::XPath->new;
$root->parse($content);
my #Baddress = $root->findvalue('//div[#id="filerDiv"]/div[#class="mailer"][2]/span/text()');
But when I print out the contents of #Baddress all of the span text is displayed on one line, like this
65 MARKET STREET, SUITE 1207,CAMANA BAY, P.O. BOX 31110 GRAND CAYMAN E9 KY1-1205 345 943 4573
Everything is being assigned to a single array element. I would like each span to be assigned to its own array element so that they may be parsed individually.
Uhg after hours of slaving over this I missed 1 essential element. The code needs to be as such
my #Baddress = $root->findvalues('//div[#id="filerDiv"]/div[#class="mailer"][2]/span/text()');
I simply had $root->findvalue which was assigning everything to 1 variable. Stupid mistake

HTML Agility get text from paragraph tags in a div

I'm trying to get the text of paragraph tags in a div using htmlagilitypack 2.28 in a windows phone 8.1 app.
The structure of div is
<div id="55">
<p> </p>
<p><span class="dropcap">W
</span><span class="zw-portion"><strong>ith the start of festive season in India</strong>, we
will also witness the f<strong>irst London Derby</strong> of the season
between the newly London rivals <strong>Chelsea and Arsenal</strong>. It will be a great chance
for Arsene Wenger to get rid of his <strong>1000</strong></span>
<strong><span class="zw-portion">th</span><span class="zw-portion"> managed </span>
<span class="zw-portion">6-0 </spa>
<span class="zw-portion">massacre</span></strong>
<span class="zw-portion"> in March,</span>
<span class="zw-portion"> </span>
<span class="zw-portion">while the Special One will be eager to continue his winning rampage
</span>
<span class="zw-portion"> </span>
<span class="zw- portion">over his “<strong>Specialist in Failure</strong>” counterpart. Although
both clubs can boast of being unbeaten this season and both clubs can take this opportunity
</span>
<span class="zw-portion"> to bring down their rival</span><span class="zw-portion">.</span></p>
<p> </p>
<p><iframe width="640" height="360" src="https://www.youtube.com/embed/zFBN8M1pCxo?
feature=oembed" frameborder="0" allowfullscreen=""></iframe></p>
<p class="zw-paragraph" data-textformat="
{"type":"text","td":"none"}"></p>
<p class="zw-paragraph" data-textformat=
{"type":"text","td":"none"}">
<span class="zw-portion">The rivalry between Chelsea and Arsenal was not as a primary London
Derby, until Chelsea rose to top of Premier League in 2000’s, when they consistently competed
against each other. The rivalry between the two clubs rose higher as compared to their
traditional rivals. Both the clubs rivalry are now not only limited to their pitch but has also
been to the fans. In 2009 survey by Football Fans Census, Arsenal fans named Chelsea as the
<strong>most disliked club</strong> </span>
<span class="zw-portion"> ahead of their traditional rivals <strong>Manchest</strong></span>
<strong> <span class="zw-portion">er United and Tottenham Hotspur</span></strong>
<span class="zw-portion">. However the report of the other camp doesn’t differ much as Chelsea
fans ranks Arsenal as their <strong>second most-disliked club</strong></span>
<strong><span class="zw-portion">.
</span></strong></p>
</div>
I want to extract only the text containined within the paragraph element within the div.
I have written the following code so far where feedurl contains the address of page from which data is to be extracted (the correct address is extracted). After that i try to get a reference to the div using it's id (which is equal to 55 always).
var feedurl = GetValue("feedurl");
string htmlPage = "asdsad";
HtmlDocument htmldoc = new HtmlDocument();
htmldoc.LoadHtml(feedurl);
htmldoc.OptionUseIdAttribute=true;
HtmlNode div = htmldoc.GetElementbyId("55");
if (div != null)
{
htmlPage += "done";
}
_content = htmlPage;
return _content;
htmldoc.GetElementbyId("55"); is returning a null reference.
I've read to use htmldoc.DocumentNode.SelectNodes([arguments]). but there is not SelectNodes method available to me. And I'm lost on how to proceed further. Please help.
HtmlAgilityPack version for WP 8.1 doesn't support SelectNodes() because that method requires XPath implementation which unfortunately missing in .NET version for WP8.1.
The solution is to use HtmlAgilityPack's LINQ API instead of Xpath. For example, to get <div> element having id attribute equals 55 :
HtmlNode div55 = htmldoc.DocumentNode
.Descendants("div")
.FirstOrDefault(o => o.GetAttributeValue("id", "")
== "55");