use querySelectorAll() to select second element of the list - javascript

Recently I am starting to learn HTML and JS. When I am leaning the document.querySelectorAll() API, I saw it can use
document.querySelectorAll('#example-container li:first-child');
to select the first child of the list which has id name is example-container.
So I thought may be
document.querySelectorAll('#example-container li:second-child');
can select the second child of the list which has id name is example-container.
But obviously it is wrong. So I am confused how can I access the second or third item of the list by using querySelectorAll()?
I post the HTML code below:
<div id="example-container">
<ul>
<li class="feature">Luxurious sized master suite</li>
<li class="feature">Oversized walk-in closet</li>
<li class="feature">Frameless Beech cabinetry with concealed hinges</li>
<li class="feature">Elegant slab white quartz countertops with large backsplash</li>
<li class="feature">Dual china sinks with Moen faucets</li>
<li class="feature">Clear frameless shower enclosures</li>
</ul>

Since you are asking what you can do to select the second or third element using query selectors, like document.querySelectorAll('#example-container li:second-child'), I am going to tell you how to select them with both css selectors and document.querySelectorAll().
You could use:
const el = document.querySelectorAll('#example-container li')[1];
to select the second element in the list. And this is probably the preferred way to do it in JavaScript.
But css has something called :nth-child() which allows you to choose a specific child in the list. In JS you could do something like:
const el = document.querySelector('#example-container li:nth-child(2)');
to select the second list item. Notice that you do not need the querySelectorAll() method.
I hope that helps a bit.

document.querySelectorAll('#example-container li') return a collection with all li nodes in example-container.
Its like array, so you can iterate it.
document.querySelectorAll('#example-container li')[index]
console.log(document.querySelectorAll('#example-container li')[1])
//its second
<div id="example-container">
<img src="img/coded-homes-logo-sm.png"
class="img-responsive" />
<img src="img/home.jpg"
class="thumbnail img-responsive push-down-top" />
<section class="description">
<p class="h5">Five bedrooms, three full baths and 3,702 square feet of living space.</p>
<p>Extra-tall double-door entry opens to an inviting and spacious foyer. Formal living and dining rooms featuring see through fireplace.</p>
<p>Large gourmet kitchen with granite countertops, stainless steel appliances with double ovens. Arrow shaped center island, huge, walk in pantry and lots of cabinets for storage. Large eating area off the kitchen for the family to enjoy meals together.</p>
<p>The front bedroom with full bathroom just outside the door. Huge family room with recessed entertainment area complete with recessed lighting and ceiling fan. The huge master suite features a soaker tub, large shower, walk-in closet and an additional over-sized walk-in closet. The master bath features split sinks with granite countertops. 3 large, secondary bedrooms and large bathroom that is great for kids to share.</p>
<p>Also includes: 3 car garage, high ceilings throughout, wired for spa in backyard, dual pane windows, new tile and carpet on bottom floor and large, upstairs laundry room. Nicely landscaped backyard with the best views in the Temescal Valley.</p>
</section>
<h2 class="h4">Features</h2>
<ul>
<li class="feature">First</li>
<li class="feature">Second</li>
<li class="feature">Frameless Beech cabinetry with concealed hinges</li>
<li class="feature">Elegant slab white quartz countertops with large backsplash</li>
<li class="feature">Dual china sinks with Moen faucets</li>
<li class="feature">Clear frameless shower enclosures</li>
</ul>

Related

Regex match group based on common groupings

Good evening,
I'm trying to group the below text so it will allow me to replace with a <ol>$1</ol>. Seems simple enough but I can't master the greediness.
Sample text (I'm aware its a repeated list, I copy+pasted for an example to show separation):
<h4>Properties</h4>
<dl><dd> Oxygen is gas at standard temperature and pressure.</dd></dl>
<h4>Testing for Oxygen</h4>
<li>A1</li>
<li>A2</li>
<li>A3</li>
<h4>Other Properties</h4>
<dl><dd> Oxygen is gas at standard temperature and pressure.</dd></dl>
<h4>Testing for Something Else</h4>
<li>B1</li>
<li>B2</li>
<li>B3</li>
The last entry can be either end-of-string or preceding another '\n'
I would like the 2 matches to be
<li>A1</li>
<li>A2</li>
<li>A3</li>
and
<li>B1</li>
<li>B2</li>
<li>B3</li>
So I can wrap in some <ol>...</ol>, simple enough. [There are other un-order lists on the page so using a temporary <lio> tag in my actual code then replacing with <li> at the end of the function].
I've gotten to the point of the below but its too greedy and starting at the first (A1's) <li> and stopping at the last (B3's) </li>
Current match:
<li>A1</li>
<li>A2</li>
<li>A3</li>
<h4>Other Properties</h4>
<dl><dd> Oxygen is gas at standard temperature and pressure.</dd></dl>
<h4>Testing for Something Else</h4>
<li>B1</li>
<li>B2</li>
<li>B3</li>
Current search string: (?!\<\/li\>.)*(\<li\>[^¬]+(\<\/li\>))(?!\<\/li\>) which captures the entire thing on Full Match (groups are a bit squiffy)
Doing this in JavaScript.
Any advice?
Thank you,
Got it licked
This does it:
(\<lio\>[\w\W]*?)\n+(\<[^l]|\0|\w|¬)

Use jsonified html as actual html in React

I'm using the wikipedia API to call information from different searches.
This is how I call it:
const api = `${proxy}http://en.wikipedia.org/w/api.php?action=parse&format=json&section=0&prop=text&page=${this.state.value}`;
Then when I get it back I'm interested in the HTML. I get that through:
jsonObject.parse.text["*"]
Then I want to use this to create a replica of the wikipedia page. This is how I try recreate the wikipedia page:
ReactDOM.render(jsonObject.parse.text["*"], document.getElementById('root'))
It doesn't work as intended. Can anyone explain why? The resulting page just has a long string. The result is something along the lines of:
<div class="mw-parser-output"><div class="shortdescription nomobile noexcerpt noprint searchaux" style="display:none">A four-wheeled motor vehicle used to transport people</div> <div role="note" class="hatnote navigation-not-searchable">For broader coverage of this topic, see Motor vehicle.</div> <div role="note" class="hatnote navigation-not-searchable">For other uses, see Car (disambiguation) and Automobile (disambiguation).</div> <p class="mw-empty-elt"> </p> <table class="infobox" style="width:22em"><tbody><tr><th colspan="2" style="text-align:center;font-size:125%;font-weight:bold">Car</th></tr><tr><td colspan="2" style="text-align:center"><img alt="401 Gridlock.jpg" src="//upload.wikimedia.org/wikipedia/commons/thumb/5/5d/401_Gridlock.jpg/300px-401_Gridlock.jpg" decoding="async" width="300" height="200" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/5/5d/401_Gridlock.jpg/450px-401_Gridlock.jpg 1.5x, //upload.wikimedia.org/wikipedia/commons/thumb/5/5d/401_Gridlock.jpg/600px-401_Gridlock.jpg 2x" data-file-width="1600" data-file-height="1066" /><div>Cars and trucks driving on Highway 401 in Ontario, Canada</div></td></tr><tr><th scope="row">Classification</th><td>Vehicle</td></tr><tr><th scope="row">Industry</th><td>Various</td></tr><tr><th scope="row">Application</th><td>Transportation</td></tr><tr><th scope="row">Fuel source</th><td>Gasoline, diesel, natural gas, electric, hydrogen, solar, vegetable oil</td></tr><tr><th scope="row">Powered</th><td>Yes</td></tr><tr><th scope="row">Self-propelled</th><td>Yes</td></tr><tr><th scope="row">Wheels</th><td>3–4</td></tr><tr><th scope="row">Axles</th><td>2</td></tr><tr><th scope="row">Inventor</th><td>Karl Benz<sup id="cite_ref-stein_1-0" class="reference">[1]</sup></td></tr></tbody></table> <p>A <b>car</b> (or <b>automobile</b>) is a wheeled motor vehicle used for transportation. Most definitions of <i>car</i> say they run primarily on roads, seat one to eight people, have four tires, and mainly transport people rather than goods.<sup id="cite_ref-2" class="reference">[2]</sup><sup id="cite_ref-OEDmotrcar_3-0" class="reference">[3]</sup> </p><p>Cars came into global use during the 20th century, and developed economies depend on them. The year 1886 is regarded as the birth year of the modern car when German inventor Karl Benz patented his Benz Patent-Motorwagen. Cars became widely available in the early 20th century. One of the first cars accessible to the masses was the 1908 Model T, an American car manufactured by the Ford Motor Company. Cars were rapidly adopted in the US, where they replaced animal-drawn carriages and carts, but took much longer to be accepted in Western Europe and other parts of the world.<sup class="noprint Inline-Template Template-Fact" style="white-space:nowrap;">[<i><span title="This claim needs references to reliable sources. (August 2019)">citation needed</span></i>]</sup> </p><p>Cars have controls for driving, parking, passenger comfort, and a variety of lights. Over the decades, additional features and controls have been added to vehicles, making them progressively more complex, but also more reliable and easier to operate.<sup class="noprint Inline-Template Template-Fact" style="white-space:nowrap;">[<i><span title="This claim needs references to reliable sources. (August 2019)">citation needed</span></i>]</sup> These include rear reversing cameras, air conditioning, navigation systems, and in-car entertainment. Most cars in use in the 2010s are propelled by an internal combustion engine, fueled by the combustion of fossil fuels. Electric cars, which were invented early in the history of the car, became commercially available in the 2000s and have the potential to cost less to buy than gasoline cars in the early 2020s.<sup id="cite_ref-4" class="reference">[4]</sup> </p><p>There are costs and benefits to car use. The costs to the individual include acquiring the vehicle, interest payments (if the car is financed), repairs and maintenance, fuel, depreciation, driving time, parking fees, taxes, and insurance.<sup id="cite_ref-racv_5-0" class="reference">[5]</sup> The costs to society include maintaining roads, land use, road congestion, air pollution, public health, health care, and disposing of the vehicle at the end of its life. Traffic collisions are the largest cause of injury-related deaths worldwide.<sup id="cite_ref-who_stats_6-0" class="reference">[6]</sup> </p><p> The personal benefits include on-demand transportation, mobility, independence, and convenience.<sup id="cite_ref-setright_7-0" class="reference">[7]</sup> The societal benefits include economic benefits, such as job and wealth creation from the automotive industry, transportation provision, societal well-being from leisure and travel opportunities, and revenue generation from the taxes. People's ability to move flexibly from place to place has far-reaching implications for the nature of societies.<sup id="cite_ref-parking_8-0" class="reference">[8]</sup> There are around 1 billion cars in use worldwide. The numbers are increasing rapidly, especially in China, India and other newly industrialized countries.<sup id="cite_ref-plunkettresearch.com_9-0" class="reference">[9]</sup></p><div class="mw-references-wrap"><ol class="references"> <li id="cite_note-stein-1"><span class="mw-cite-backlink"><b>^</b></span> <span class="error mw-ext-cite-error" lang="en" dir="ltr">Cite error: The named reference <code>stein</code> was invoked but never defined (see the help page). </span></li> <li id="cite_note-2"><span class="mw-cite-backlink"><b>^</b></span> <span class="reference-text"><cite class="citation book">Fowler, H.W.; Fowler, F.G., eds. (1976). <i>Pocket Oxford Dictionary</i>. Oxford University Press. ISBN <bdi>978-0198611134</bdi>.</cite><span title="ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&rft.genre=book&rft.btitle=Pocket+Oxford+Dictionary&rft.pub=Oxford+University+Press&rft.date=1976&rft.isbn=978-0198611134&rfr_id=info%3Asid%2Fen.wikipedia.org%3ACar" class="Z3988"></span><style data-mw-deduplicate="TemplateStyles:r886058088">.mw-parser-output cite.citation{font-style:inherit}.mw-parser-output .citation q{quotes:"\"""\"""'""'"}.mw-parser-output .citation .cs1-lock-free a{background:url("//upload.wikimedia.org/wikipedia/commons/thumb/6/65/Lock-green.svg/9px-Lock-green.svg.png")no-repeat;background-position:right .1em center}.mw-parser-output .citation .cs1-lock-limited a,.mw-parser-output .citation .cs1-lock-registration a{background:url("//upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Lock-gray-alt-2.svg/9px-Lock-gray-alt-2.svg.png")no-repeat;background-position:right .1em center}.mw-parser-output .citation .cs1-lock-subscription a{background:url("//upload.wikimedia.org/wikipedia/commons/thumb/a/aa/Lock-red-alt-2.svg/9px-Lock-red-alt-2.svg.png")no-repeat;background-position:right .1em center}.mw-parser-output .cs1-subscription,.mw-parser-output .cs1-registration{color:#555}.mw-parser-output .cs1-subscription span,.mw-parser-output .cs1-registration span{border-bottom:1px dotted;cursor:help}.mw-parser-output .cs1-ws-icon a{background:url("//upload.wikimedia.org/wikipedia/commons/thumb/4/4c/Wikisource-logo.svg/12px-Wikisource-logo.svg.png")no-repeat;background-position:right .1em center}.mw-parser-output code.cs1-code{color:inherit;background:inherit;border:inherit;padding:inherit}.mw-parser-output .cs1-hidden-error{display:none;font-size:100%}.mw-parser-output .cs1-visible-error{font-size:100%}.mw-parser-output .cs1-maint{display:none;color:#33aa33;margin-left:0.3em}.mw-parser-output .cs1-subscription,.mw-parser-output .cs1-registration,.mw-parser-output .cs1-format{font-size:95%}.mw-parser-output .cs1-kern-left,.mw-parser-output .cs1-kern-wl-left{padding-left:0.2em}.mw-parser-output .cs1-kern-right,.mw-parser-output .cs1-kern-wl-right{padding-right:0.2em}</style></span> </li> <li id="cite_note-OEDmotrcar-3"><span class="mw-cite-backlink"><b>^</b></span> <span class="error mw-ext-cite-error" lang="en" dir="ltr">Cite error: The named reference <code>OEDmotrcar</code> was invoked but never defined (see the help page). </span></li> <li id="cite_note-4"><span class="mw-cite-backlink"><b>^</b></span> <span class="reference-text"><cite class="citation web"><a rel="nofollow" class="external text" href="https://cleantechnica.com/2019/08/09/ev-price-parity-coming-soon-claims-vw-executive/">"EV Price Parity Coming Soon, Claims VW Executive"</a>. <i>CleanTechnica</i>. 9 August 2019<span class="reference-accessdate">. Retrieved <span class="nowrap">10 August</span> 2019</span>.</cite><span title="ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Ajournal&rft.genre=unknown&rft.jtitle=CleanTechnica&rft.atitle=EV+Price+Parity+Coming+Soon%2C+Claims+VW+Executive&rft.date=2019-08-09&rft_id=https%3A%2F%2Fcleantechnica.com%2F2019%2F08%2F09%2Fev-price-parity-coming-soon-claims-vw-executive%2F&rfr_id=info%3Asid%2Fen.wikipedia.org%3ACar" class="Z3988"></span><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r886058088"/></span> </li> <li id="cite_note-racv-5"><span class="mw-cite-backlink"><b>^</b></span> <span class="reference-text"><cite class="citation web"><a rel="nofollow" class="external text" href="https://web.archive.org/web/20091007121101/http://www.racv.com.au/wps/wcm/connect/racv/Internet/Primary/my%2Bcar/advice%2B_%2Binformation/vehicle%2Boperating%2Bcosts/">"Car Operating Costs"</a>. RACV. Archived from <a rel="nofollow" class="external text" href="http://www.racv.com.au/wps/wcm/connect/racv/Internet/Primary/my+car/advice+_+information/vehicle+operating+costs/">the original</a> on 7 October 2009<span class="reference-accessdate">. Retrieved <span class="nowrap">22 December</span> 2009</span>.</cite><span title="ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&rft.genre=unknown&rft.btitle=Car+Operating+Costs&rft.pub=RACV&rft_id=http%3A%2F%2Fwww.racv.com.au%2Fwps%2Fwcm%2Fconnect%2Fracv%2FInternet%2FPrimary%2Fmy%2Bcar%2Fadvice%2B_%2Binformation%2Fvehicle%2Boperating%2Bcosts%2F&rfr_id=info%3Asid%2Fen.wikipedia.org%3ACar" class="Z3988"></span><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r886058088"/></span> </li> <li id="cite_note-who_stats-6"><span class="mw-cite-backlink"><b>^</b></span> <span class="reference-text"><cite class="citation book">Peden, Margie; Scurfield, Richard; Sleet, David; Mohan, Dinesh; Hyder, Adnan A.; Jarawan, Eva; Mathers, Colin, eds. (2004). <a rel="nofollow" class="external text" href="http://who.int/violence_injury_prevention/publications/road_traffic/world_report/en/"><i>World report on road traffic injury prevention</i></a>. World Health Organization. ISBN <bdi>92-4-156260-9</bdi><span class="reference-accessdate">. Retrieved <span class="nowrap">24 June</span> 2008</span>.</cite><span title="ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&rft.genre=book&rft.btitle=World+report+on+road+traffic+injury+prevention&rft.pub=World+Health+Organization&rft.date=2004&rft.isbn=92-4-156260-9&rft_id=http%3A%2F%2Fwho.int%2Fviolence_injury_prevention%2Fpublications%2Froad_traffic%2Fworld_report%2Fen%2F&rfr_id=info%3Asid%2Fen.wikipedia.org%3ACar" class="Z3988"></span><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r886058088"/></span> </li> <li id="cite_note-setright-7"><span class="mw-cite-backlink"><b>^</b></span> <span class="error mw-ext-cite-error" lang="en" dir="ltr">Cite error: The named reference <code>setright</code> was invoked but never defined (see the help page). </span></li> <li id="cite_note-parking-8"><span class="mw-cite-backlink"><b>^</b></span> <span class="reference-text"><cite class="citation book">Jakle, John A.; Sculle, Keith A. (2004). <i>Lots of Parking: Land Use in a Car Culture</i>. University of Virginia Press. ISBN <bdi>0-8139-2266-6</bdi>.</cite><span title="ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&rft.genre=book&rft.btitle=Lots+of+Parking%3A+Land+Use+in+a+Car+Culture&rft.pub=University+of+Virginia+Press&rft.date=2004&rft.isbn=0-8139-2266-6&rft.aulast=Jakle&rft.aufirst=John+A.&rft.au=Sculle%2C+Keith+A.&rfr_id=info%3Asid%2Fen.wikipedia.org%3ACar" class="Z3988"></span><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r886058088"/></span> </li> <li id="cite_note-plunkettresearch.com-9"><span class="mw-cite-backlink"><b>^</b></span> <span class="reference-text"><cite class="citation web"><a rel="nofollow" class="external text" href="https://web.archive.org/web/20110722031051/http://www.plunkettresearch.com/automobiles%20trucks%20market%20research/industry%20overview">"Automobile Industry Introduction"</a>. Plunkett Research. Archived from <a rel="nofollow" class="external text" href="http://www.plunkettresearch.com/Industries/AutomobilesTrucks/AutomobileTrends/tabid/89/Default.aspx">the original</a> on 22 July 2011.</cite><span title="ctx_ver=Z39.88-2004&rft_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Abook&rft.genre=unknown&rft.btitle=Automobile+Industry+Introduction&rft.pub=Plunkett+Research&rft_id=http%3A%2F%2Fwww.plunkettresearch.com%2FIndustries%2FAutomobilesTrucks%2FAutomobileTrends%2Ftabid%2F89%2FDefault.aspx&rfr_id=info%3Asid%2Fen.wikipedia.org%3ACar" class="Z3988"></span><link rel="mw-deduplicated-inline-style" href="mw-data:TemplateStyles:r886058088"/></span> </li> </ol></div> <!-- NewPP limit report Parsed by mw1289 Cached time: 20191013083710 Cache expiry: 2592000 Dynamic content: false Complications: [vary‐revision‐sha1] CPU time usage: 0.332 seconds Real time usage: 0.499 seconds Preprocessor visited node count: 1184/1000000 Preprocessor generated node count: 0/1500000 Post‐expand include size: 22522/2097152 bytes Template argument size: 3602/2097152 bytes Highest expansion depth: 13/40 Expensive parser function count: 4/500 Unstrip recursion depth: 0/20 Unstrip post‐expand size: 12133/5000000 bytes Number of Wikibase entities loaded: 0/400 Lua time usage: 0.152/10.000 seconds Lua memory usage: 3.95 MB/50 MB --> <!-- Transclusion expansion time report (%,ms,calls,template) 100.00% 476.128 1 -total 18.96% 90.271 3 Template:Cite_book 11.75% 55.942 1 Template:Pp-semi-vandalism 10.35% 49.266 2 Template:Cn 9.87% 47.004 1 Template:Short_description 9.05% 43.105 1 Template:Pagetype 8.69% 41.353 2 Template:Fix 7.57% 36.060 6 Template:Broken_ref 6.32% 30.079 1 Template:Infobox_machine 5.53% 26.318 4 Template:Category_handler --> </div>
React will block HTML inserted by javascript by default. If you want to get around this, you need to use the dangerouslySetInnerHTML prop on the parent of your content.
Example:
// data from fetch
let data;
return <div dangerouslySetInnerHTML={data}></div>
When you do this, make sure that you trust the HTML source. If you add user generated HTML to your site like this, your site will be vulnerable to XSS attacks.

Not registering bolded text inside json item using JavaScript

So I have an list with items where the years are bolded. But when i put them in JSON and later I set the text in HTML, the text is not bolded. In the link ,now I have the bold tags and the text . This is confusing . Can i make this work ?
<div class="year-list">
<h3 class="time-line">Here's a time line of Dr. Borlaug's life:</h3>
<div class="big-list">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li><b>1938 </b> - Marries wife of 69 years Margret Gibson. Gets laid off due to budget cuts. Inspired by Elvin Charles Stakman, he returns to school study under Stakman, who teaches him about breeding pest-resistent plants.</li>
<li><b>1941 </b> - Tries to enroll in the military after the Pearl Harbor attack, but is rejected. Instead, the military asked his lab to work on waterproof glue, DDT to control malaria, disenfectants, and other applied science.</li>
<li><b>1942 </b> - Receives a Ph.D. in Genetics and Plant Pathology</li>
<li><b>1944 </b> - Rejects a 100% salary increase from Dupont, leaves behind his pregnant wife, and flies to Mexico to head a new plant pathology program. Over the next 16 years, his team breeds 6,000 different strains of disease resistent wheat - including different varieties for each major climate on Earth.</li>
<li><b>1945 </b> - Discovers a way to grown wheat twice each season, doubling wheat yields</li>
<li><b>1953 </b> - crosses a short, sturdy dwarf breed of wheat with a high-yeidling American breed, creating a strain that responds well to fertalizer. It goes on to provide 95% of Mexico's wheat.</li>
<li><b>1962 </b> - Visits Delhi and brings his high-yielding strains of wheat to the Indian subcontinent in time to help mitigate mass starvation due to a rapidly expanding population</li>
<li><b>1970 </b> - receives the Nobel Peace Prize</li>
<li><b>1983 </b> - helps seven African countries dramatically increase their maize and sorghum yields</li>
<li><b>1984 </b> - becomes a distinguished professor at Texas A&M University</li>
<li><b>2005 </b> - states "we will have to double the world food supply by 2050." Argues that genetically modified crops are the only way we can meet the demand, as we run out of arable land. Says that GM crops are not inherently dangerous because "we've been genetically modifying plants and animals for a long time. Long before we called it science, people were selecting the best breeds."</li>
<li></li>
</ul>
</div>
</div>
This is the part of mine JSON.
{"divHoldingTitle":{"title":"Dr. Norman Borlaug","textSave":"The man who saved a billion lives"},"imageHolder":{"theBigPicture":"./images/smiling-people.jpg","textUnderPicture":"Dr. Norman Borlaug, second from left, trains biologists in Mexico on how to increase wheat yields - part of his life-long war on hunger."},"bigList":{"itemList":[{"item":"<b>1914 </b> - Born in Cresco, Iowa"},{"item":"<li><b>1933 </b> - Leaves his family\'s farm to attend the University of Minnesota, thanks to a Depression era program known as the\'National Youth Administration\'"}]}}
for(i in obj.bigList.itemList){
$('li').text(obj.bigList.itemList[i].item);
}
};
The problem is this.
Screenshot of the problem
As you can see. The lists have 1933 - Leaves his family's farm to..
But it is not bolded.
I am not sure how to solve this problem. I am using JavaScript .
This is due to using .text() method - it removes all formatting tags.
Use html() instead:
$('li').html(obj.bigList.itemList[i].item);

Get javascript accordion to work with 1 ID

I'm using a nice accordion script from TYMPANUS for my website though the difference is that I am using it multiple times on 1 page like:
<div id="st-accordion" class="st-accordion">
<ul>
<li>
Flowers <span class="st-arrow">View <b>Details</b></span>
<div class="st-content">
<p>She packed her seven versalia, put her initial into the belt and made
herself on the way. When she reached the first hills of the Italic Mountains, she had
a last view back on the skyline of her hometown Bookmarksgrove, the headline of
Alphabet Village and the subline of her own road, the Line Lane.</p>
</div>
</li>
</ul>
</div>
<div id="st-accordion" class="st-accordion">
<ul>
<li>
Flowers <span class="st-arrow">View <b>Details</b></span>
<div class="st-content">
<p>She packed her seven versalia, put her initial into the belt and made
herself on the way. When she reached the first hills of the Italic Mountains, she had
a last view back on the skyline of her hometown Bookmarksgrove, the headline of
Alphabet Village and the subline of her own road, the Line Lane.</p>
</div>
</li>
</ul>
</div>
Please see this FIDDLE 01
As you can see I have 2 separate elements (I need it to be separate) using that accordion but because the ID is the same, you can clearly see that the second accordion isn't working.
Javascript for this fiddle:
$(function() {
$('#st-accordion').accordion();
});
So to get it working, I created separate ID's for each element like in this FIDDLE 02
Javascript for this fiddle:
$(function() {
$('#st-accordion-01, #st-accordion-02').accordion();
});
BUT I don't like having to always create an extra / different ID, so it there a way to get FIDDLE 01 working without having to resort to FIDDLE 02? ... Or is this just not possible?
*The Javascripts posted above are at the very bottom of the javascript section in jsfiddle
There can not / must not be elements with the same id name in one page.
http://www.w3.org/TR/html5/elements.html#the-id-attribute
The id attribute specifies its element's unique identifier (ID). The
value must be unique amongst all the IDs in the element's home subtree
and must contain at least one character. The value must not contain
any space characters.
So to fix your problem, just remove the same ids and just leave the class st-accordion
http://jsfiddle.net/5h559dyj/3/
$(function() {
$('.st-accordion').accordion();
});

Can you count elements by image name using length() in jQuery?

I'm trying to put together a review "summary" section that totals the number of 5 star, 4 star, 3 star reviews etc.. What I need to do is count the instances of each "review level" on a product page and output the number. e.g. If a product has 50 reviews and 14 of them were 5 stars, I need to output that figure to the page as "14".
The only differentiator across reviews is not by an id or class, but the image name it outputs (which is the number of stars). See the image file names below for what I mean:
<ol class="ProductReviewList">
<li class="">
<h4 class="ReviewTitle">
Cool hammock!
<img src="http://cdn2.bigcommerce.com/rc71b9995f4a706510d16ad47d2472c26eb88e9bf/themes/HealthBeauty/images/IcoRating4.png" alt="">
</h4>
<p class="Meta">
Posted by Matina Keller on 6th Jan 2014
</p>
<p>I love this hammock! I got the single brazilian for my courtyard out the side and it fits snug between two patio posts. I can easily put it up and take it down whenever i want. It's really comfortable and easy to fall asleep in. The material is of very high quality and far better than my old hammock. Delivery was about 4 days to adelaide FYI.</p>
<hr>
</li> <li class="Alt">
<h4 class="ReviewTitle">
So comfortable!
<img src="http://cdn2.bigcommerce.com/rc71b9995f4a706510d16ad47d2472c26eb88e9bf/themes/HealthBeauty/images/IcoRating5.png" alt="">
</h4>
<p class="Meta">
Posted by Kendra Lovell on 17th Dec 2013
</p>
<p>I bought one of these for my daughter and she loves it. It's really comfortable and the colours are so pretty. Thanks siesta hammocks.</p>
<hr>
</li> <li class="">
<h4 class="ReviewTitle">
Great customer service and product!
<img src="http://cdn2.bigcommerce.com/rc71b9995f4a706510d16ad47d2472c26eb88e9bf/themes/HealthBeauty/images/IcoRating5.png" alt="">
</h4>
<p class="Meta">
Posted by Susan Knight on 20th Nov 2013
</p>
<p>I must have had a million questions about this but the staff on the online chat answered all of them! Really good customer service and ordering system. The hammock itself is really good quality. So relaxing in the afternoon sun. Got the double hook kits and put it up between some wooden posts we already had under our pergola. Got the frame too in case we want to put it somewhere else. Really easy to assemble and is very sturdy. All up it's been a great experience shopping with siesta so thanks.</p>
<hr>
</li>
</ol>
See at the very end how images are either IcoRating4.png or IcoRating5.png
I want to know if I can use .length() to count elements in the document not by id or class but by a string in their filename, or by image name or some variant like that. Is this possible?
I've put together a fiddle here if that helps
Thanks!
Sure can:
var count = $('img[src$="IcoRating4.png"]').length;
ref: http://api.jquery.com/attribute-ends-with-selector/

Categories

Resources