searching for elements - document

I was assigned homework in which I had to take the given HTML file and create a Javascript file which would search for words within a div class. I have to use both document.getElementById() and .querySelectorAll.

You need to get the elements with: document.querySelectorAll(".main");
and then you need to get the search with document.getElementById("searchtext"), and then you can add use addEventListener to make it run your function when a click event occurs:
function Search()
{
var elements = document.querySelectorAll(".main");
let search = document.getElementById('searchtext').value;
for (var i = 0; i < elements.length; i++)
{
if(elements[i].innerHTML.indexOf(search) > - 1)
{
alert('found');
}
}
}
document.getElementById('searchbutton').addEventListener('click', Search);
<body>
<div class="main">
<p>The Phoenix Suns are a professional basketball team based in Phoenix, Arizona. They are members of the ...</p>
<p>The Suns have been generally successful since they began play as an expansion team in 1968. In forty years of play they have posted ...</p>
<p>On January 22, 1968, the NBA awarded expansion franchises to an ownership group from Phoenix and one from Milwaukee. ...</p>
<ul>
<li>Richard L. Bloch, investment broker/real estate developer...</li>
<li>Karl Eller, outdoor advertising company owner and former...</li>
<li>Donald Pitt, Tucson-based attorney;</li>
<li>Don Diamond, Tucson-based real estate investor.</li>
</ul>
<p>Page by New Person. <br /> Some (all) information taken from Wikipedia.</p>
</div>
<hr />
<div>
Search for text:
<input id="searchtext" type="text" />
<button id="searchbutton">Search</button>
</div>
</body>

You have to store the value you are searching for in a variable (search). You get this value by calling the property .value of an <input> tag, which you can select, as you did already by using document.getElementById("searchtext").
Then store the elements you want to search in in another variable, in this case an array by using document.getElementsByClassName("main") (notice the getElementsByClassName which indicates it returns a collection).
And you have to call your function somewhere. I just added it to the button onclick event in this line:
<button id="searchbutton" onclick="search()">Search</button>
function search() {
var search = document.getElementById("searchtext").value;
var elements = document.getElementsByClassName("main");
for (var i = 0; i < elements.length; i++) {
if (elements[i].innerHTML.indexOf(search) > -1) {
alert('found');
}
}
}
<div class="main">
<p>The Phoenix Suns are a professional basketball team based in Phoenix, Arizona. They are members of the ...</p>
<p>The Suns have been generally successful since they began play as an expansion team in 1968. In forty years of play they have posted ...</p>
<p>On January 22, 1968, the NBA awarded expansion franchises to an ownership group from Phoenix and one from Milwaukee. ...</p>
<ul>
<li>Richard L. Bloch, investment broker/real estate developer...</li>
<li>Karl Eller, outdoor advertising company owner and former...</li>
<li>Donald Pitt, Tucson-based attorney;</li>
<li>Don Diamond, Tucson-based real estate investor.</li>
</ul>
<p>Page by New Person. <br /> Some (all) information taken from Wikipedia.</p>
</div>
<hr />
<div>
Search for text:
<input id="searchtext" type="text" />
<button id="searchbutton" onclick="search()">Search</button>
</div>

So you should add a onclick function on the button which should be like this <button id=“searchbutton”, onclick=“Search()”>Search</button>
And also i don’t think “document.getElementById(“searchtext”).querySelectorAll(“main”);” would work beacuse you should do it in seperate variables like one for search text one for selection. Hope this helps!

get the value of the input field with document.getElementById("searchtext").value
document.querySelectorAll('.main') returns a NodeList on which you can use the values() function that will return an iterator over all the node values in the list
use then for(var el of elements.values()) and check for every element if it occurs
Demo:
function search() {
var searchText = document.getElementById("searchtext").value,
elements = document.querySelectorAll('.main');
for(var el of elements.values()) {
var idx = el.innerHTML.indexOf(searchText);
if(idx != -1){
console.log("Found at: ", idx);
}
}
}
<head>
<script src = "first.js" type = "text/javascript"></script>
<link href= "dirststyle.css" type = "text/css" rel = "stylesheet"/>
</head>
<body>
<div class="main">
<p>The Phoenix Suns are a professional basketball team based in Phoenix, Arizona. They are members of the ...</p>
<p>The Suns have been generally successful since they began play as an expansion team in 1968. In forty years of play they have posted ...</p>
<p>On January 22, 1968, the NBA awarded expansion franchises to an ownership group from Phoenix and one from Milwaukee. ...</p>
<ul>
<li>Richard L. Bloch, investment broker/real estate developer...</li>
<li>Karl Eller, outdoor advertising company owner and former...</li>
<li>Donald Pitt, Tucson-based attorney;</li>
<li>Don Diamond, Tucson-based real estate investor.</li>
</ul>
<p>Page by New Person. <br /> Some (all) information taken from Wikipedia.</p>
</div>
<hr />
<div>
Search for text:
<input id="searchtext" type="text" />
<button id="searchbutton" onclick="search()">Search</button>
</div>
</body>

Related

How can I change the colour of a specific div based off the entry in my database? For a real-time parking lot map

I am not sure where to begin in regards to this type of development. I have developed my react-nodejs app which is successfully connected with my postgresql database.
An visual example UI of what I'm trying to attain
I would like to create a map that reflects a parking lot, and each parking spot should change colour based on the information in the database at that current time. For example, on Feb 9 at 9:25pm parking spot #4 is occupied, so my map will show the parking spot as red, meanwhile parking spot #5 is unoccupied, so the spot is green.
My frontend is made with react, and I have edited the elements with css.
For my database, right now I have my parking spot table, I have the current date, parking spot number, and the occupied column set as boolean. Does boolean make sense for the occupied column, in this regard?
The code for the table:
CREATE TABLE parking_spots (
parking_spot_id serial NOT NULL PRIMARY KEY,
parking_spot_number int serial NOT NULL,
occupancy boolean,
createdAt timestamp DEFAULT CURRENT_TIMESTAMP
);
The code for my parking lot is as follows:
const ParkingLot = () => {
// function abc(n) { console.log(n); }
const navigate = useNavigate(); // the navigation hook
const handleClick = event => {
event.preventDefault();
// navigate({value}); //redirects to the /home address
navigate('/')
}
const handleClickFwd = event => {
event.preventDefault();
// navigate({value}); //redirects to the /home address
navigate('/home/booking')
}
return (
<div className='flex-container'>
<div className='row'>
<div className="flex-container-accessories">
<div class="flex-accessories">
<div
className='backButton'
id="icon"
onClick={handleClick}
>
<ArrowBackIosIcon
className="icon"
sx={{fontSize: 'medium'}}
/>
</div>
<div
className='fwdButton'
id="icon"
onClick={handleClickFwd}
>
<ArrowForwardIosIcon
className="icon"
sx={{fontSize: 'medium'}}
/>
</div>
</div>
</div>
</div>
<div className='row'>
<header>
<div>
<h2> 1st Floor </h2>
<h2> 2 Spots Available </h2>
</div>
</header>
</div>
<div className="row">
<div className='flex-accessories'>
<div className='dropDown'>
<Selecter
className='dropDown'
/>
</div>
</div>
<div className="flex-accessories">
<div className='dropDownRight'>
<SelectType
className='dropDownRight'
/>
</div>
</div>
</div>
<div className='row'>
<ParkingMap/>
</div>
<div className="row">
<ParkingLegend/>
</div>
</div>
);
};
export default ParkingLot;
Any advice, guidance, or tutorials would be greatly appreciated.

How to access element within a signOn window within a PowerBI page with selenium vba

When I try to target the email element by class or id, it will throw an error:
run-time error '438': object doesn't support this property or method
There are no iframes and I can't seem to switch to a window either(that I am seeing).
Here is vba code:
Set bot = New Selenium.ChromeDriver
bot.start baseUrl:="https://app.powerbi.com/singleSignOn"
bot.Get "/"
Application.Wait Now + TimeValue("00:00:3")
Dim FindBy As New Selenium.By
With bot
.FindElementsByCss(".pbi-text-input").Click
.FindElementsById("email").SendKeys ("testing")
end with
Html code:
</head>
<body>
<div id="emailCollection" class="emailBlock" style="display: none;"> <!-- The popup window -->
<div class="emailLogoAndName">
<object type="image/svg+xml" data="13.0.17576.29/images/PowerBI_MasterLogo.svg"></object>
<label>Power BI</label>
</div>
<div class="emailDetailArea">
<div class="emailDetailHeader"><label>Enter your email, we'll check if you need to create a new account.</label></div>
<div class="emailDetailContent">
<div class="emailDetailContentArea">
<div class="emailContentInput">
<div class="emailInputTitle">Email</div>
<div><input class="pbi-text-input" type="text" placeholder="Enter email" id="email"></div>
<div class="emailInputError" style="display: none;"></div>
</div>
<div class="emailContentDisclaimers">
<div class="emailDisclaimer1">
By proceeding you acknowledge that if you use your organization's email, your organization may have rights to access and manage your data and account.
<span class="learnMoreBtn" onmouseover="setPosition(event)">
Learn more about using your organization's email
<span class="learnMoreText">
<b>Using your organization's email address to sign up</b>
<p>If you use an email address provided by an organization you are affiliated with (like an employer or school), the owner of the email domain may (i) manage and administer your account, including modifying and terminating your access and (ii) access and process your data, including the contents of your communications and files. Your directory data (including name, signup date, and email) may be visible to other users of these services within your organization.
</p>
</span>
</span>
</div>
<div class="emailDisclaimer2">
By clicking Submit, you agree to these <a href='https://go.microsoft.com/fwlink/?LinkID=870457&clcid=0x409' target='_blank'>terms and conditions</a> and allow Power BI to get your user and tenant details. <a href='https://go.microsoft.com/fwlink/?LinkID=521839&clcid=0x409' target='_blank'>Microsoft Privacy Statement</a>
</div>
</div>
</div>
<button class="pbi-fluent-button primary" id="submitBtn" onclick="submitEmail()">Submit</button>
</div>
</div>
<div class="emailLogoArea">
<object type="image/svg+xml" data="13.0.17576.29/images/PowerBI_MasterLogo.svg"></object>
</div>
</div>
</body>
</html>
url: https://app.powerbi.com/singleSignOn
As the website is Power BI enabled, 3 seconds may not be enough for the element to be clickable.
You may increase the wait time to 10 secs and you can use either of the following Locator Strategies:
Using FindElementByCss:
bot.FindElementByCss("input.pbi-text-input#email[placeholder='Enter email'][type='text']").SendKeys ("Red")
Using FindElementByXPath:
bot.FindElementByXPath("//input[#class='pbi-text-input' and #id='email'][#placeholder='Enter email' and #type='text']").SendKeys ("Red")

python selenium find text of child of previous parent

I have the following document:
<div class="background-section ">
<h3 class='t-16'> Company1 </h3>
<p class="title t-14"> JobType </p>
<div class="background-section ">
<h3 class='t-16'> Company2 </h3>
<p class="title t-14"> JobType2 </p>
by trying the following:
driver.find_element_by_xpath("//p[contains(text(), 'JobType')]")
I still need to extract "Company1" text too but I could not relate
I want the output to find "Company1" related to JobType
Any idea?
You can use xpath here as it is used to identify and navigate nodes in HTML.
Try below code and let me know if it works for you :-
Mytext = driver.find_element_by_xpath("//p[contains(text(),'JobType')]/parent::div/h3").text
The output will be -

Processing dynamically added elements Material Design Lite

First, the code:
$(document).ready(function() {
$('#member_pattern').hide();
$('.add-member').click(function() {
var clone = $('#member_pattern').clone(), cont = $('.members-cont');
$(cont).append(clone);
$(cont).find('#member_pattern').show(200, function() {
$(this).attr('id', '');
componentHandler.upgradeAllRegistered();
});
});
});
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<link rel="stylesheet" href="https://storage.googleapis.com/code.getmdl.io/1.0.2/material.blue-indigo.min.css" />
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:300,400,500,700" type="text/css">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<script src="https://storage.googleapis.com/code.getmdl.io/1.0.0/material.min.js"></script>
<div class="members-cont">
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text" id="first_name_<?php echo $member->id; ?>" value="<?php echo $member['first_name']; ?>"/>
<label class="mdl-textfield__label" for="first_name_<?php echo $member->id; ?>">Имя</label>
</div>
</div>
<button class="add-member add-member-top mdl-button mdl-js-button mdl-button--fab mdl-js-ripple-effect mdl-button--colored">
<i class="material-icons">add</i>
</button>
<div id="member_pattern" class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input class="mdl-textfield__input" type="text" id="[name]_[id]" value=""/>
<label class="mdl-textfield__label" for="[name]_[id]">Имя</label>
</div>
Objective:
By pressing a button on the page dynamically insert another field [.mdl-textfield], you want to apply the "material design" on Google
All is good, but the methods
componentHandler.upgradeAllRegistered ();
or
componentHandler.upgradeDom ();
in any does not want to renew, re-emerged, the elements on the page.
I also was having problems cloning an element and getting it to work correctly. What I did was to remove the MDL specific classes from the div and change it to a generic class name that I could select on.
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
became
<div class="upgradeTextField">
Then in javascript, after cloning the element, I selected for those divs within the cloned element and added the MDL specific classes to them. After that, running componentHandler.upgradeDom() seemed to work.
var textFieldUpgrades = cloned.querySelectorAll('.upgradeTextField');
if(textFieldUpgrades) {
for(var i=0;i<textFieldUpgrades.length;++i) {
textFieldUpgrades[i].className = 'mdl-textfield mdl-js-textfield mdl-textfield--floating-label';
}
}
componentHandler.upgradeDom();
I haven't verified this, but it seems that when you clone an existing element within the dom that has been upgraded by MDL previously, it won't upgrade it when you add the cloned object to the DOM. So that's why I simply removed the MDL classes so it wouldn't be upgraded beforehand.
Alternatively, if you need it upgraded beforehand and still want to clone it. Then what you can do is to remove the attribute 'data-upgraded' and class 'is-upgraded' from your element after you clone it. Then when you run the componentHandler.upgradeDom() it should upgrade it. So, instead of just setting the class name as in the above snippet, you'd simply remove the upgrade info:
textFieldUpgrades[i].setAttribute('data-upgraded','');
textFieldUpgrades[i].className = textFieldUpgrades[i].className.replace(/is-upgraded/g,'');
This seemed to work for me.
Thanks for the answer, but it turned out to solve it more concise way
var index = $('.member-section').length;
var clone = $('.member-section-pattern').clone();
$(clone)
.removeClass('member-section-pattern')
.find(':not([data-upgraded=""])').attr('data-upgraded', '');
$('.members-cont').append(clone);
$(clone).show(200, function() {
componentHandler.upgradeAllRegistered();
});

Multiple Foursquare 'save' buttons on one page

I am working on a site that displays a list of venues and would like to add a Foursquare 'save' button for each venue in the list. Is it possible to show multiple Foursquare 'save' buttons on a single page? I've tried creating multiple vCard blocks (one for each venue) and inserting a 'save' button in each block but the locations are not being picked up.
After inspecting the source of the widgets.js and widgets.asyncbundle.js I discovered that setting thedata-context atribute of the 'Save to Foursquare' button to the ID of the VCard will link these two. Like so:
<div id="hcard-Station-Amsterdam-Centraal" class="vcard">
<span class="fn">
<span class="given-name">Station Amsterdam Centraal</span>
</span>
<div class="adr">
<div class="street-address">stationsplein 15</div>
<span class="locality">Amsterdam</span>,
<span class="region">Amsterdam</span> ,
<span class="postal-code">1012AB</span>
</div>
</div>
<div id="hcard-Jaarbeursplein" class="vcard">
<span class="fn">
<span class="given-name">Jaarbeursplein</span>
</span>
<div class="adr">
<div class="street-address">Jaarbeursplein</div>
<span class="locality">Utrecht</span>,
<span class="region">Utrecht</span>,
<span class="postal-code">3521AL</span>
</div>
</div>
Save to foursquare
Save to foursquare
But for the fact that this isn't documented, it may be changed in the near future.
Try this with "data-vid":
<!-- Place this anchor tag where you want the button to go -->
<br />
All In PartyRadio StudioSave to foursquare
<br />
Sing Sing Music HallSave to foursquare
<br />
Retro KlubSave to foursquare
<br />
Tisza DokkSave to foursquare
<br />
Zöld Zsiráf KultúrpartSave to foursquare
<!-- Place this script somewhere after the anchor tag above. If you have multiple buttons, only include the script once. -->
<script type='text/javascript'>
(function() {
window.___fourSq = {"uid":"606"};
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'http://platform.foursquare.com/js/widgets.js';
s.async = true;
var ph = document.getElementsByTagName('script')[0];
ph.parentNode.insertBefore(s, ph);
})();
</script>
The in-progress docs for the save-to-foursquare widget are accessible # https://developer.foursquare.com/overview/widgets. They'll be cleaned up over time, but should be good enough to help this and future widget-related questions =).
In particular, documentation about the "data-context" attribute you need will be pushed to the linked page soon.

Resources