GUJ Discussões   :   últimos tópicos   |   categorias   |   GUJ Respostas

Busca Interna por conteudo na própria página html


#1

Pessoal,

Primeiramente gostaria de agradecer pela ajuda de vocês se conseguirem resolver este problema. Caso não puderem ajudar, desde já me desculpo por terem tomado o tempo de vocês. Tentei resolver este problema, mas realmente não tenho ideia de como fazer.

Estou fazendo um trabalho para a faculdade e não estou conseguindo fazer uma busca interna na própria página html. Eu criei uma collection de objetos e estou exibindo a mesma na página. Até ai tudo certo. O problema é que preciso buscar os elementos desta collection por nome e nome científico e exibir apenas o resultado da busca.

A princípio as regras de funcionamento da página são:

Quando o usuário clicar no botão “Search Animals” e o campo estiver branco ou nulo a mensagem “No matches found.” deve ser exibida. Caso contrário, se o campo estiver preenchido com o nome ou nome científico (case insensitive) o animal pesquisado deve ser exibido.

Quando o usuário clicar no botão “Show All” todos os animais devem ser exibidos. No loading da página, todos os animais também devem ser exibidos.

Obs: Este código só funciona do Firefox.

Link com os arquivos e abaixo o código dos mesmos caso não optem por fazer o download.
https://drive.google.com/file/d/1aOxpJXaVS8WgT1kSmMacCICrOTBZHC3t/view?usp=sharing

Html code:

WEBD-1000 - Virtual Zoo

WEBD-1000

Advanced DOM Manipulation

    <section id="content">
        <h2>Virtual Zoo</h2>

            <input name="search_text" id="search_text" placeholder="Search for common or scientific name.">
            <button name="search_button" id="search_button">Search Animals</button>
            <button name="show_all_button" id="show_all_button">Show All</button>

        <ul id="animals">
            <li>No matches found.</li>
        </ul>
    </section> 
    
    <footer>
        <p>Glutton Media - Copywrong 2015</p>
    </footer> <!-- #footer end -->
</div> <!-- #wrapper end -->

JS code:

/*
Script name: Zooland.js
Description: Used to display animals and related info from an XML file
Author: Fabio Cunha
Date Created: November 21, 2017
*/

// Takes the elements needed to insert a new li to the ul
function buildUnorderedList(ul,newLi,commonNameH3, scientificNameH4,descriptionBlock){
newLi.appendChild(commonNameH3);
newLi.appendChild(scientificNameH4);
newLi.appendChild(descriptionBlock);
//newLi.appendChild(images);

}

/*

  • Hides all of the elements.
    */
    function hideElements()
    {
    var elementsForm = document.getElementsByClassName(“animals”);

    for(var i = 0; i < elementsForm.length; i++){
    elementsForm[i].style.display = “none”;
    }

}

function load() {

var oneAnimal = document.getElementById("search_text").value;

// loads xml file
var zooland_xml = loadXML('zooland.xml');

// Let's do a bit of sanity checking:

// Ensure that the xml has loaded correctly.
console.log(zooland_xml);

// the root element
zoolandRoot = zooland_xml.documentElement;

// log file
console.log(zoolandRoot, zoolandRoot.children[0], zoolandRoot.children[0].innerHTML);

// Find the name of the first animal and write it to the console.
var first_animal = zooland_xml.getElementsByTagName('animal')[0];
var common_name_element = first_animal.getElementsByTagName('common_name')[0];
var common_name = common_name_element.firstChild.nodeValue;
console.log('The common name of the first animal is: ' + common_name);

// create the elements we need according to html file
var section = document.getElementsByTagName("section")[0];
var ul = document.createElement("ul");
section.appendChild(ul);

// checks if root element is not null and displays information in the webpage
for (var i = 0; i < zoolandRoot.children.length; i++) {

	// creates content
	var newLi = document.createElement("li");
	var commonNameH3 = document.createElement("h3");
	var scientificNameH4 = document.createElement("h4");
	var descriptionBlock = document.createElement("blockquote");

	// gets the values from XML
	// Common name
    var animal_name = zoolandRoot.getElementsByTagName("common_name")[i].textContent;
	commonNameH3.textContent = animal_name;

	// Scientific name
    var scientific_name = zoolandRoot.getElementsByTagName("scientific_name")[i].textContent;
	scientificNameH4.textContent = scientific_name;
	
	// Description
    var description = zoolandRoot.getElementsByTagName("description")[i].textContent;
	descriptionBlock.textContent = description;

	// Images
    var img = zoolandRoot.getElementsByTagName("images")[i];
	
	// builds unordered list
	buildUnorderedList(ul, newLi, commonNameH3, scientificNameH4,descriptionBlock);

	// Create img element, set src to "imgChild" value
	for (var x = 0; x < img.children.length; x++) {
		var imgChild = img.getElementsByTagName("image")[x].textContent;
		var imageElement = document.createElement("img");
		imageElement.src = 'images/' + imgChild;
		newLi.appendChild(imageElement);
	}
	
	ul.appendChild(newLi);

}//for loop end

}

// Other event listeners can go here.
document.addEventListener(“DOMContentLoaded”, load);

CSS code

html{
font-family: Arial, Verdana, sans-serif;
}

#wrapper {
width: 650px;
margin-left: auto;
margin-right: auto;
padding: 0 1em;
border: 1px solid gray;
}

header {
border-bottom: 1px dashed gray;
margin-bottom: 1em;
}

header h1 {
margin-top: 0.5em;
margin-bottom: 0;
}

header h2 {
margin-top: 0.1em;
}

#content {
float: left;
width: 650px;
}

#content h2 {
font-family: Arial, sans-serif;
font-size: 1.2em;
margin-top: 1em;
}

#content p {
margin: 1em;
}

footer {
border-top: 1px dashed gray;
clear: both;
text-align: center;
}

footer p {
margin-bottom: 1em;
}

img {
padding: 10px;
margin: 0 10px 10px 0;
border: 1px solid gray;
}

#content ul {
list-style: none;
margin: 0 0 1em 0;
padding: 0;
}

#content ul li {
padding: 1em;
border: 2px solid #eeeeee;
}

/zebra_background/
#content li:nth-child(even){
background-color: #eeeeee;
}

/*
.zebra_background {
background-color: #eeeeee;
}
*/

blockquote {
margin: 0 0 1em 0;
font-style: italic;
}

input#search_text {
width: 220px;
}

xml file

<?xml version="1.0" encoding="UTF-8"?> Elephant Elephantidae Elephants are a family in the order Proboscidea in the class Mammalia. They were once classified along with other thick skinned animals in a now invalid order, Pachydermata. There are three living species: the African Bush Elephant, the African Forest Elephant (until recently known collectively as the African Elephant), and the Asian Elephant (also known as the Indian Elephant). Other species have become extinct since the last ice age, which ended about 10,000 years ago, the Mammoth being the most well-known of these. elephant13.jpg elephant22.jpg elephant32.jpg elephant42.jpg Emu Dromaius novaehollandiae The Emu is the largest bird native to Australia and the only extant member of the genus Dromaius. It is also the second-largest extant bird in the world by height, after its ratite relative, the ostrich. The soft-feathered, brown, flightless birds reach up to 2 m (6.5 ft) in height. The Emu is common over most of mainland Australia, although it avoids heavily populated areas, dense forest and arid areas. Emus can travel great distances at a fast, economical trot and, if necessary, can sprint at 50 km/h (30 mph) for some distance at a time. They are opportunistically nomadic and may travel long distances to find food; they feed on a variety of plants and insects. emu12.jpg emu26.jpg emu46.jpg emu23.jpg Lion Panthera leo The lion is a member of the family Felidae and one of four big cats in the genus Panthera. With exceptionally large males exceeding 250 kg (550 lb) in weight, it is the second-largest living cat after the tiger. Wild lions currently exist in sub-Saharan Africa and in Asia with a critically endangered remnant population in northwest India, having disappeared from North Africa, the Middle East, and western Asia in historic times. Until the late Pleistocene (about 10,000 years ago), the lion was the most widespread large land mammal beside humans. They were found in most of Africa, much of Eurasia from western Europe to India, and the Bering land bridge and, in the Americas, from the Yukon to Peru. lion51.jpg lion24.jpg lion43.jpg lion46.jpg Orca Orcinus orca The Orca (Orcinus orca), also referred to as the killer whale, and less commonly as the blackfish or grampus, is a toothed whale belonging to the oceanic dolphin family, of which it is the largest member. Orcas are found in all oceans, from Arctic and Antarctic regions to tropical seas. Orcas have a diverse diet, although individual populations often specialize in particular types of prey. Some feed exclusively on fish, while others hunt marine mammals like pinnipeds, and even large whales. They have been known to attack baleen whale calves. Orcas are regarded as apex predators, lacking natural predators. Orcas are highly social; some populations are composed of matrilineal family groups which are the most stable of any animal species. Their sophisticated hunting techniques and vocal behaviors, which are often specific to a particular group and passed across generations, have been anthropomorphically described as manifestations of culture. orca1.jpg orca2.jpg orca3.jpg orca4.jpg Panda Ailuropoda melanoleuca The Giant Panda is a mammal classified in the bear family, Ursidae, native to central-western and southwestern China. The panda was previously thought to be a member of the Procyonidae. It is easily recognized by its large, distinctive black patches around the eyes, over the ears, and across its round body. Though belonging to the order Carnivora, the panda has a diet which is 99% bamboo. Pandas may eat other foods such as honey, eggs, fish, yams, shrub leaves, oranges and bananas. Giant pandas live in a few mountain ranges in central China, in Sichuan, Shaanxi, and Gansu provinces. They once lived in lowland areas, but farming, forest clearing, and other development now restrict giant pandas to the mountains. panda31.jpg panda23.jpg panda3.jpg Tiger Panthera tigris The tiger is a mammal of the Felidae family, the largest of four "big cats" in the Panthera genus. Native to much of eastern and southern Asia, the tiger is an apex predator and an obligate carnivore. Reaching up to 4 metres (13 feet) in total length and weighing up to 300 kg (660 pounds), tigers are comparable in size to the biggest extinct felids. Aside from their great bulk and power, their most recognizable feature is the pattern of dark vertical stripes that overlays near-white to reddish-orange fur, with lighter underparts. tiger18.jpg tiger62.jpg tiger33.jpg tiger14.jpg Toad Bufonidae Toad refers to a number of species of amphibians. A distinction is often made between frogs and toads by their appearance, prompted by the convergent adaptation among so-called toads to dry environments. For instance, toads often have leathery skin for better water retention, and a brown coloration for camouflage. Many so-called toads also burrow, which requires further adaptations. toad11.jpg toad72.jpg toad34.jpg toad94.jpg Turtle Chordata Sauropsida Turtles are reptilians of the Order Testudines (all living turtles belong to the crown group Chelonia), most of whose body is shielded by a special bony or cartilaginous shell developed from their ribs. The Order Testudines includes both extant (living) and extinct species. The earliest known turtles date from 215 million years ago, making turtles one of the oldest reptile groups and a more ancient group than lizards and snakes. About 300 species are alive today, and some are highly endangered. turtle1.jpg turtle2.jpg turtle63.jpg turtle34.jpg Zebra Equus quagga Zebras are odd-toed ungulates of the Equidae family native to eastern, southern and southwestern Africa. They are best known for their distinctive white and black stripes, which come in different patterns unique to each individual. They are generally social animals and can be seen in small harems to large herds. zebra1.jpg zebra9.jpg zebra3.jpg zebra4.jpg

JS xml_functions

// A cross-browser “To String” helper for xml node objects.
// Using console.dirxml() is an alternative way to inspect XML.
// Uses strict mode: https://goo.gl/xmOUmj
function xmlToString(node) {
‘use strict’;

if (node.xml) { // Only IE supports this property.
return node.xml;
} else if (XMLSerializer) { // Firefox supports this.
var my_serializer = new XMLSerializer();
return my_serializer.serializeToString(node);
} else {
alert(‘Your browser does not support XML serialization.’);
return ‘’;
}
}

// Synchronously loads the received XML document as a DOM Document object
// and returns it.
// Uses strict mode: https://goo.gl/xmOUmj
function loadXML(filename) {
‘use strict’;

var xhttp;

if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else { // Only really old browsers like IE6 need this:
xhttp = new ActiveXObject(‘Microsoft.XMLHTTP’);
}

// Note: Setting the third argument to false turns on synchronous
// fetch mode, which is being phased out (deprecated).
xhttp.open(‘GET’, filename, false);
xhttp.send();
return xhttp.responseXML;
}